There are following way to sort list of strings in decreasing order of their length in java 8.
- First convert Arrays to list using Arrays.asList() method.
- Now get the Stream data from List using arrayList.stream() method.
- Here Java 8 method Comparator.comparing(String::length) is used to sort the list of strings based on their length and reversed() method is reverse this string.
- Now Collectors.toList() method collect all the list of string.
- Print the list of string.
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class SortByLength {
public static void main(String[] args) {
List<String> listOfstrings = Arrays.asList("java", "spring", "hibernate", "spring boot", "servlet");
List<String> sortedStrings = listOfstrings.stream().sorted(Comparator.comparing(String::length).reversed())
.collect(Collectors.toList());
System.out.println("Sorted list of strings by length in decreasing order :- " + sortedStrings);
}
}
Output :-
Sorted list of strings by length in decreasing order :- [spring boot, hibernate, servlet, spring, java]