How do I sort an an array of String
based on the strings sizes i.e String#length
?
Asked
Active
Viewed 3,178 times
2

user7610
- 25,267
- 15
- 124
- 150

hysteriaistic
- 85
- 1
- 3
- 10
-
possible duplicate of [Custom String Length Comparator: what's my mistake?](http://stackoverflow.com/questions/5925532/custom-string-length-comparator-whats-my-mistake) – Gábor Bakos Jan 29 '15 at 12:23
-
4Java 8: `Arrays.sort(strings, Comparator.comparing(String::length));`. – Marko Topolnik Jan 29 '15 at 12:42
-
similar to http://stackoverflow.com/questions/8938235/java-sort-an-array – user7610 Mar 25 '17 at 12:15
2 Answers
3
In Java 8, this can be done in one line,
Arrays.sort(randomString, (s1,s2) -> Integer.compare(s1.length(), s2.length()));
If you want reverse order (higher-length to lower-length),
change it to,
Arrays.sort(randomString, (s1,s2) -> Integer.compare(s2.length(), s1.length()));
Another approach,
use Comparator.comparing(String::length)
,
Arrays.sort(yourArray, Comparator.comparing(String::length));
to reverse the order,
Arrays.sort(yourArray, Comparator.comparing(String::length).reversed());

Sufiyan Ghori
- 18,164
- 14
- 82
- 110
-
1Maybe a one-liner, but doesn't sort in-place and needlessly copies the data. – Marko Topolnik Jan 29 '15 at 13:06
2
You can implement a Comparator that uses the length and use Arrays.sort with your Comparator. The Comparator could look like this:
class StringComparator implements Comparator<String>{
public int compare(String o1, String o2){
return Integer.compare(o1.length(), o2.length());
}
}
Now you could sort with the following call:
Arrays.sort(strings, new StringComparator());

Mnementh
- 50,487
- 48
- 148
- 202