2

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

user7610
  • 21,109
  • 9
  • 108
  • 131
hysteriaistic
  • 75
  • 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
  • 17,317
  • 13
  • 76
  • 106
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
  • 48,735
  • 46
  • 144
  • 201