-1

I have a list of linkedlist.

    List<LinkedList<File1>> lists = 
        Collections.synchronizedList(new ArrayList<LinkedList<File1>>());

each linkedlist contains objects of type File1.

class File1
{
    int dist,nod;       
}

Can anyone help me to sort the elements based on dist.

I thought of using collections.sort() but this cannot be used in this case, so can anyone suggest a better idea?

yaitloutou
  • 1,691
  • 19
  • 23
Divyashree
  • 15
  • 4

3 Answers3

6

Iterate over each linkedlist in your arraylist, then sort it. But to make sure that the elements are sorted on dist, you should implement Comparable:

public class File1 implements Comparable<File1>
{
    int dist, nod;

    public int compareTo(File1 f)
    {
        return Integer.compare(dist, f.dist);
    }
}
Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
  • thnks a lot :) it was vry useful :) – Divyashree Apr 13 '12 at 08:17
  • @Divyashree: Welcome to StackOverflow. If someone answered your question that way that it solved your problem, you can accept the answer by hitting the tick under the score of the question. You will see that the tick will become green, this means you accepted the answer. – Martijn Courteaux Apr 13 '12 at 10:57
4

You could sort either the inner or outer lists using the Collections.sort() method that accepts a Comparator.

public static void sort(List list, Comparator c)

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
3

Use Collections.sort() with a custom comparator that compares the dist value of each object.

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
lrAndroid
  • 2,834
  • 18
  • 27