Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
Advertisements
