- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements