How to sort array of strings by their lengths following longest to shortest pattern in Java


At first, let us create and array of strings:

String[] strArr = { "ABCD", "AB", "ABCDEFG", "ABC", "A", "ABCDE", "ABCDEF", "ABCDEFGHIJ" }

Now, for longest to shortest pattern, for example ABCDEFGHIJ, ABCDEFG, ABCDEF, etc.; get the length of both the string arrays and work them like this:

Arrays.sort(strArr, (str1, str2) → str2.length() - str1.length());

The following is an example to sort array of strings by their lengths with longest to shortest pattern in Java:

Example

import java.util.Arrays;
public class Demo {
   public static void main(String[] args) {
      String[] strArr = { "ABCD", "AB", "ABCDEFG", "ABC", "A", "ABCDE", "ABCDEF", "ABCDEFGHIJ" };
      System.out.println("Sorting array on the basis of their lengths (longest to shortest) = ");
      Arrays.sort(strArr, (str1, str2) → str2.length() - str1.length());
      Arrays.asList(strArr).forEach(System.out::println);
   }
}

Output

Sorting array on the basis of their lengths (longest to shortest) =
ABCDEFGHIJ
ABCDEFG
ABCDEF
ABCDE
ABCD
ABC
AB
A

Updated on: 30-Jul-2019

214 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements