• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sorting custom objects with Java collections

 
M Burke
Ranch Hand
Posts: 404
  • Mark post as helpful
  • send pies
  • 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
 
Dmitry Melnik
Ranch Hand
Posts: 328
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How about this?

java.util.Collections.sort(yourList,aComparator);
[ August 03, 2004: Message edited by: Dmitry Melnik ]
 
Ben Ethridge
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • 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
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13061
6
  • Mark post as helpful
  • send pies
  • 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: 404
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, I will take a look at it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic