Win a copy of Bad Programming Practices 101 (e-book) this week in the Beginning Java forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Sorted Collections using multiple conditions?  RSS feed

 
Ranch Hand
Posts: 416
  • 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 );

}
}
 
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.
 
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: 416
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, guys
 
That's my roommate. He's kinda weird, but he always pays his half of the rent. And he gave me this tiny ad:
Why should you try IntelliJ IDEA ?
https://coderanch.com/wiki/696337/IntelliJ-IDEA
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!