• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • Devaka Cooray
Saloon Keepers:
  • Ganesh Patekar
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • salvin francis
Bartenders:
  • Ron McLeod
  • Frits Walraven
  • Pete Letkeman

Sorted Collections using multiple conditions?  RSS feed

 
Ranch Hand
Posts: 418
  • 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: 418
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, guys
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!