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
Register / Login


JavaRanch » Java Forums » Java » Java in General
Reply 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: 375
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: 12324
    
    1
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: 375
Thanks, I will take a look at it.
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Sorting custom objects with Java collections
 
Similar Threads
Lots of Data :: Out of Memory
How to stop parsing of a file with SAX
interoperability to what extent?
to find the datatype of given string in runtime
help in creating DAL