• Post Reply Bookmark Topic Watch Topic
  • New Topic

Sorting based on multiple parameters  RSS feed

 
Manish Hatwalne
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
 
Rob Spoor
Sheriff
Posts: 21116
85
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...
 
Kim Kantola
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!
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!