aspose file tools*
The moose likes Java in General and the fly likes Sorting custom objects with Java collections Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Sorting custom objects with Java collections" Watch "Sorting custom objects with Java collections" New topic
Author

Sorting custom objects with Java collections

M Burke
Ranch Hand

Joined: Jun 25, 2004
Posts: 388
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
Dmitry Melnik
Ranch Hand

Joined: Dec 18, 2003
Posts: 328
How about this?

java.util.Collections.sort(yourList,aComparator);
[ August 03, 2004: Message edited by: Dmitry Melnik ]
Ben Ethridge
Ranch Hand

Joined: Jul 28, 2003
Posts: 108
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
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12835
    
    5
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

Joined: Jun 25, 2004
Posts: 388
Thanks, I will take a look at it.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Sorting custom objects with Java collections