How to sort LinkedList <String>?

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

Input Example:

this
is
just
a
test

Output Example:

a
is
this
just
test

I try to do this with the method Comparable<LinkedList<String>>and compareTo, but I do not 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>();

// [...] 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;
            }

        }

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

but I get this as output:

a
is
just
test
this

How can I fix this problem?

+5
source share
4 answers

, . Comparator<String> :

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

, , :

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

, LinkedList , ArrayList.

+3

:

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

:

Collections.sort(list, new Q3_sorting());

, . List ( , ), , JVM, , .

, , , String , . , , :)

+7

Collections.sort(list, comparator). Comparator<String> a Comparator<LinkedList<String>>. , javadoc of Collections.sort ( , ).

+6

, , , , . , . , Collections.sort().

-1

All Articles