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


At first, let us create and array of strings:

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

Now, for shortest to longest pattern, for example A, AB, ABC, ABCD, etc.; get the length of both the string arrays and work them like this:

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

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

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 (shortest to longest) =");
      Arrays.sort(strArr, (str1, str2) -> str1.length() - str2.length());
      Arrays.asList(strArr).forEach(System.out::println);
   }
}

Output

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

Updated on: 30-Jul-2019

527 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements