How can I sort an array first by length, then alphabetically?
I have a list of things with numbers on them, and I am currently getting:
Something1 Something10 Something2 Something3
Whereas I want to get:
Something1 Something2 Something3 Something10
public class MyComparator implements Comparator<String>{
@Override
public int compare(String o1, String o2) {
if (o1.length() > o2.length()) {
return 1;
} else if (o1.length() < o2.length()) {
return -1;
}
return o1.compareTo(o2);
}
}
Then use:
Collections.sort(yourList, new MyComparator());
Here's a concise Java 8 solution:
List<String> list = Arrays.asList("Something1", "Something10", "Something2", "Something3");
list.sort(Comparator.comparing(String::length).thenComparing(String::compareTo));
Or, case-insensitive version:
list.sort(Comparator.comparing(String::length).thenComparing(String::compareToIgnoreCase));
Create a Comparator which compares by length first and if the lengths are the same, uses the String.compareTo().
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