• Post Reply Bookmark Topic Watch Topic
  • New Topic

Sorted Collections using multiple conditions?  RSS feed

 
M Burke
Ranch Hand
Posts: 410
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to sort a collection based on multiple properties. I can sort using one, but how do I expand it to include many properties? I have a sort order; property one, then two, then three.

This is what I have, sorting using one property...

class StringComparator implements Comparator {
public int compare( Object object1, Object object2 ) {

return ((String) object1).compareTo( (String) object2 );

}
}
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are various ways, but I would do something like this:

or possibly

You can modify these depending on whether the properties you're working with are primitives or reference types, and whether those types implement Comparable or not.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A more flexible approach would be to apply the Composite pattern, such as done in this article: http://robobruin.blogspot.com/2007/09/composite-comparator-fun-with-generics.html
 
M Burke
Ranch Hand
Posts: 410
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, guys
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!