Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Multi Level Sorting of a ArrayList

 
Vinitha Pai
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I have a ArrayList containing the values retreived from the DB. I need to sort the data in two levels. The primary level is the field containing the Date and if the sorted values have the same dates the data needs to be sorted with the field containing Names. How do I do it? I have used the comparator to sort individually how do I club the results?

Thanks,
Vinitha
 
Jeff Rummings
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Either a Comparator or Comparable (whatever is more appropriate) will do the job. If you're using a Comparator, you could do something like this:

 
Vinitha Pai
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the response. But I need to retain the result of the first sort and then sort upon it. The second sort criteria should not effect the first result if there is no similar data.
 
Petrus Pelser
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sort first according to date, then take the sorted list and sort that again using a simple conditional statement on the date and name. (while date is equal => sort name)
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Vinitha Pai:
Thanks for the response. But I need to retain the result of the first sort and then sort upon it. The second sort criteria should not effect the first result if there is no similar data.


Did you try Arman's suggestion ? I think you will find it does what you want.
 
Campbell Ritchie
Sheriff
Pie
Posts: 48981
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And read the useful information in the Java Tutorial.
 
Vinitha Pai
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you all for your timely reply. Yes! It did work. But instead of compareTo I used compare() because this wasnt working when I needed to change the sortorder.

Cheers,
Vinitha
 
Bill Shirley
Ranch Hand
Posts: 457
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You may also be able to have the database sort it for you before it is returned, depending on how your data is persisted.

Most tools overlie SQL and us it to fetch. If you have access to the SQL (EJB QL, etc.) you can have the database do the heavy lifting before it is retrieved.

This could be particularly useful if you are dealing with 10s of 1000s of records, or if you want to only return a subset of the records.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic