Search code examples
javasortinglinked-listcomparable

How to sort LinkedList<String>?


I need to sort the Strings of a LinkedList by the length of the Strings, but would like to keep the order of same-length strings (not sorted lexicographically).

Sample input:

this
is
just
a
test

Sample Output:

a
is
this
just
test

I am trying to do this with a Comparable<LinkedList<String>> and a compareTo method, but I don't get the correct output (mine still sorts it lexicographically)

public class Q3_sorting implements Comparable<LinkedList<String>> {
    Scanner keyboardScanner = null;
    LinkedList<String> fileList = new LinkedList<String>();

// [...] some code here

public int compareTo(LinkedList<String> o) {
        // TODO Auto-generated method stub
        o = fileList;

        for (int i = 0; i < fileList.size() -1; i++) {
            if (fileList.get(i).length() == o.get(i+1).length()) {
                return 0;
            }
            if (fileList.get(i).length() > o.get(i+1).length()) {
                return -1;
            }
            if (fileList.get(i).length() < o.get(i+1).length()) {
                return 1;
            }

        }

I then use
Q3_sorting sort = new Q3_sorting(args);
Collections.sort(sort.fileList); in my main method. I then print the list out...

but I get this as output:

a
is
just
test
this

How would I rectify this problem?


Solution

  • You are sorting strings, not lists of strings. To do this, you need to define a Comparator<String> to compare two strings by their length as follows:

    public class ByLength implements Comparator<String> {
      @Override
      public int compare(String a, String b) {
        return a.length() - b.length();
      }
    }
    

    Then, to sort the list, you need to call:

    Collections.sort(sort.fileList, new ByLength());
    

    Also note that sorting a LinkedList is very inefficient and you should use an ArrayList instead.