How do I sort strings based on their length?
You can sort strings based on their length using the sort method combined with a custom comparator. In the code snippet below we are going to use the Arrays.sort() method. We pass an array of string to the sort() method and also a lambda expression as the custom comparator. Here is how you’d do it […]
Article by Wayan · Source: Kode Java ↗
You can sort strings based on their length using the sort method combined with a custom comparator. In the code snippet below we are going to use the Arrays.sort() method. We pass an array of string to the sort() method and also a lambda expression as the custom comparator.
Here is how you’d do it in Java:
package org.kodejava.util;
import java.util.Arrays;
public class SortStringsExample {
public static void main(String[] args) {
String[] strings = {"Hello", "World", "Java", "is", "beautiful"};
// Sort the array based on string length
Arrays.sort(strings, (a, b) -> a.length() - b.length());
// Print the sorted array
Arrays.stream(strings).forEach(System.out::println);
}
}
In this example, an array of strings is sorted in increasing order of their lengths. If you want to sort them in descending order, you can change the comparator to (a, b) -> b.length() - a.length().
The output of the code snippet above is:
is
Java
Hello
World
beautiful
Comments 0
Share your questions, experiences, or feedback about this article.
Sign in with Google to leave a comment.
Sign in with Google
No comments yet. Be the first to share your feedback.