Win a copy of Learning Regular Expressions this week in the General Computing forum!
  • 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:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

Sorting based on multiple parameters  RSS feed

 
Ranch Hand
Posts: 2596
Android Firefox Browser Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am little brain-dead today. Having problems writing comparator that will do comparison (for sorting) for multiple parameters.

Here is what I need to do - I have object MyObj with several fields. now I need to sort a collection of such objects based on list of fields supplied.
So say if I want to sort MyObj collection based on fields "date" & "price" - similar to SQL "...order by date, price" - how do I do this?

Or in other words, how do I write comparator for following method?



any pointers, help would be highly appreciated!

TIA,
- Manish
 
Sheriff
Posts: 21461
96
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Manish Hatwalne
Ranch Hand
Posts: 2596
Android Firefox Browser Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, but will it work for ordering of second level? let me check...
 
Ranch Hand
Posts: 276
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey!

I was just trying to figure out how to do this and found this post on JavaRanch. I did a test and sure enough it did the trick.

This is a super solution, would have been hard to figure out.
Thanks so much for posting it here.

For anyone else who may be searching, if you have a list of objects that contain multiple values in the object that you want to sort, it will work like this, if you were sorting the following object, and the sort was by lastName, firstName, room number :

these objects
Ojbect 1: Lastname = Smith, First Name=Mark, Room = 312
Object 2: Lastname = Smith, First Name=Mark, Room = 101
Object 3: Lastname = Bartlett, First Name = James, Room = 202
Object 4: LastName = Bartlett, First Name= Bridget, Room = 202

Would sort like this :

Bartlett, Bridget 202
Bartlett, James 202
Smith, Mark 101
Smith, Mark 212

Hope this helps someone else.
Thanks for the help!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!