Learnitweb

Java program to sort a list of strings according to the increasing order of their length

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class SortByLength {
    public static void main(String[] args) {
        List<String> words = Arrays.asList("apple", "banana", "kiwi", "cherry", "mango");

        List<String> sortedWords = words.stream()
                .sorted((s1, s2) -> Integer.compare(s1.length(), s2.length())) // Sort by length
                .collect(Collectors.toList());

        System.out.println(sortedWords);
    }
}

Alternative: Using Comparator.comparing()

A more concise way:

List<String> sortedWords = words.stream()
        .sorted(Comparator.comparing(String::length))
        .collect(Collectors.toList());