• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Sorting custom objects with Java collections

 
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Lets say I have a custom data object...

class Data{
String firm;
String date;
int grossSales;
int netSales;
}

And I want to drop a bunch of these data objects into a Java Collection (Vector? ArrayList? not sure).
How can I sort it on the avalable fields, first by firm, then date?

Thanks
 
Ranch Hand
Posts: 328
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
How about this?

java.util.Collections.sort(yourList,aComparator);
[ August 03, 2004: Message edited by: Dmitry Melnik ]
 
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I just used the Comparator the way Dmitry described. It's not simple to understand at first, i.e. takes some reading and study (in the javadocs and looking at some simple examples), but it's very powerful once you get the hang of it.

A google search on "Comparator" will probably find you what you need.

Ben
 
Author and all-around good cowpoke
Posts: 13078
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Like Ben said, Comparators are powerful whenyou get the hang of it. Here is something I just wrote to create Comparators for sorting ArrayLists of File objects.

Bill
 
M Burke
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks, I will take a look at it.
 
reply
    Bookmark Topic Watch Topic
  • New Topic