Sort array first by length then alphabetically in Java
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().