Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

arrays

I am trying to sort an array of strings according to their length using Arrays.sort(), but this sorts the strings lexicographically rather than by length. Here is my code:

S = "No one could disentangle correctly"
String W[] = S.split(" ");
Arrays.sort(W);

After sorting :

correctly
could
disentangle
no
one

but what I want is

no  //length = 2
one //length = 3
could //length = 4 and likewise
correctly
disentangle

How can I get the above output? Please give answer for JDK 1.7 & JDK1.8.

like image 284
Zohra Khan Avatar asked Mar 08 '16 11:03

Zohra Khan


People also ask

Can we sort string array using arrays sort?

To sort an array of strings in Java, we can use Arrays. sort() function.

Can you use sort () on an array?

Just like numeric arrays, you can also sort string array using the sort function. When you pass the string array, the array is sorted in ascending alphabetical order.


3 Answers

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.

like image 102
matt Avatar answered Sep 30 '22 14:09

matt


Alternative to and slightly simpler than matt's version

Arrays.sort(W, Comparator.comparingInt(String::length));
like image 23
Manos Nikolaidis Avatar answered Sep 30 '22 15:09

Manos Nikolaidis


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
    }
});
like image 40
mmuzahid Avatar answered Sep 30 '22 15:09

mmuzahid