aspose file tools*
The moose likes Java in General and the fly likes How to sort a list of lists Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "How to sort a list of lists" Watch "How to sort a list of lists" New topic
Author

How to sort a list of lists

Sneha Kashyap
Greenhorn

Joined: May 06, 2009
Posts: 22
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

Joined: Nov 24, 2005
Posts: 14688
    
  16

You have to tell the Collections how you want this list to be sorted. What about making a Comparator<List<String>> ?


[My Blog]
All roads lead to JavaRanch
Sneha Kashyap
Greenhorn

Joined: May 06, 2009
Posts: 22
Thanks
Hey can you please help me with some sample code.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39409
    
  28
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

Joined: May 06, 2010
Posts: 100
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

Joined: Oct 27, 2005
Posts: 19720
    
  20

Given two List<String> objects the main question is indeed how they should be compared. The following is an often used algorithm (pseudo code):


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to sort a list of lists