2

How do I sort an an array of String based on the strings sizes i.e String#length?

user7610
  • 25,267
  • 15
  • 124
  • 150
hysteriaistic
  • 85
  • 1
  • 3
  • 10

2 Answers2

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
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