Sort ArrayList of strings by length in java 8?

There are following way to Sort ArrayList of strings by 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 Comparator.comparing(String::length) is used to sort the list of strings based on their length.
  • Through forEach() loop we print the output.
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class SortWithLength {
	public static void main(String[] args) {
		List<String> listString = Arrays.asList("hibernate", "java", "spring", "servlet", "jsp");
		listString.stream().sorted(Comparator.comparing(String::length)).forEach(System.out::println);
	}
}

Output :-
jsp
java
spring
servlet
hibernate