Sort Strings by Length in Java 8 Using Stream API

Learn how to sort strings by Length in Java 8 Using Stream API, here Comparator.comparing() method sorts strings according to their length. The reversed() method changes the sorting order from ascending to descending, resulting in the longest strings appearing first.

Code Explanation (Step-by-Step)

  • Arrays.asList() converts the array of strings into a List.
  • stream() creates a Stream from the List.
  • Comparator.comparing(String::length) compares strings based on their length.
  • reversed() changes the order from ascending to descending.
  • Collectors.toList() collects the sorted strings into a new List.
  • Now, the sorted list is printed.
				
					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]

Reverse the Sorting Order

				
					import java.util.Arrays;
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((s1, s2) -> Integer.compare(s2.length(), s1.length()))
                .collect(Collectors.toList());

        System.out.println(sortedStrings);
    }
}