• Post Reply Bookmark Topic Watch Topic
  • New Topic

sorting of a collection of Java classes  RSS feed

 
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a collection of Java classes. And this Java Class has fields: name, value, startDate, StartTime, amount, and etc.
I like to perform various sorting on this collection. For example: sort startDate in descending order, then sort name in asceding order. Is there any existing Java collection classes that can help me on this sorting task?
Thanks in advance.
 
Ranch Hand
Posts: 154
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Create a comparator for every kind of sort you desire and use Collections.sort() utility. That is an optimized sort algorithm. I think it uses merge sort - but i'm not sure, check it out.
 
Ranch Hand
Posts: 2676
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Collections.sort will help you sort a Collection of objects, but you have to do some prep work first. There are two ways that you can take advantage of this class. Option 1 is to implement the comparable interface on the object that you will be sorting. The option that seems more likely to be useful in your case is to create a class that implements the Comparator interface for each way you would compare objects. You would then pass your collection and the Comparator object that contains your comparison logic.
[ November 14, 2002: Message edited by: Matthew Phillips ]
 
tumbleweed and gunslinger
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is a comparator class I use to sort within a bean. As you can see, I use a specific class and method as the basis for the sort.

[ November 26, 2002: Message edited by: David Yutzy ]
[ November 26, 2002: Message edited by: Cindy Glass ]
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!