• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to sort a list of lists

 
Sneha Kashyap
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am trying to sort a list of lists


the data in the list is something like this
{[def,ghi,xml],
[abc,ghi,cde],
[cat,ghi,der]}
I want the data to be
{[abc,ghi,cde],
[cat,ghi,der],
[def,ghi,xml],}
I am not able to use Collections.sort(listOfLists)
Any help is greatly appreciated.
Thanks in advance.
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have to tell the Collections how you want this list to be sorted. What about making a Comparator<List<String>> ?
 
Sneha Kashyap
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks
Hey can you please help me with some sample code.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49367
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sneha Kashyap wrote:Thanks
Hey can you please help me with some sample code.
No. We believe people learn better if they show us what ideas they have first.

Write whatever you have: if you have no code, write down in small words how to sort your list of lists. Note this text with the lines is full of small words.
 
Istvan Kovacs
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since you want to sort the lists based on the 1st String they contain (at least, this is my understanding), have a class implement Comparator<List<String>> as Christophe has suggested, in its method extract the 1st item from each list, and (since Strings are Comparable) just invoke Be sure to handle the case when either of the lists is empty.
Pseudo-code:
 
Rob Spoor
Sheriff
Pie
Posts: 20546
56
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given two List<String> objects the main question is indeed how they should be compared. The following is an often used algorithm (pseudo code):
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic