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 useQ3_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?
You should create a comparator:
public class Q3_sorting implements Comparator<String> {
public int compare(String a, String b) {
return a.length() - b.length();
}
And then sort it with the method:
Collections.sort(list, new Q3_sorting());
Note that what you want to do is sort the Strings inside the List. By implementing a comparator of List (or a comparable, as it works on the same purpose here) what you are telling the JVM is that you want to compare different List's.
You could also achieve your objective by implementing a Comparable in the class to sort, but you can't as long as String is final so you cannot extend. Therefore there is no other way than to implement a Comparator, which is simpler too :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With