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.
To sort an array of strings in Java, we can use Arrays. sort() function.
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.
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.
Alternative to and slightly simpler than matt's version
Arrays.sort(W, Comparator.comparingInt(String::length));
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
}
});
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