How to sort String array by length using Arrays.sort()

Alternative to and slightly simpler than matt's version

Arrays.sort(W, Comparator.comparingInt(String::length));

Simply changing the parameter position we can sort in descending order.

Arrays.sort(W, (a,b)->b.length() - a.length());

For java 8 and above

 Arrays.sort(W, (a, b)->Integer.compare(a.length(), b.length()));

A more concise way is to use Comparator.comparingInt from Mano's answer here.


If you are using JDK 1.8 or above then you could use lambda expression like matt answer. But if you are using JDK 1.7 or earlier version try to write a custom Comparator like this:

String S = "No one could disentangle correctly";
String W[] = S.split(" ");
Arrays.sort(W, new java.util.Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        // TODO: Argument validation (nullity, length)
        return s1.length() - s2.length();// comparision
    }
});

Tags:

Java

Arrays