Search code examples
javajava-stream

How to sort a list of lists using the Stream API?


I want to output all names starting with the letter "A" and sort them in reverse alphabetical order using the Stream API. The result should look like this: Ann, Andrew, Alex, Adisson. How do I do this?

List<List<String>> list = Arrays.asList(
            Arrays.asList("John", "Ann"),
            Arrays.asList("Alex", "Andrew", "Mark"),
            Arrays.asList("Neil", "Adisson", "Bob")
    );
    List<List<String>> sortedList = list.stream()
            .filter(o -> o.startsWith("A"))
            Comparator.reverseOrder());
    System.out.println(list);

Solution

  • Since you are assigning the result to a List<List<String>> it appears you want to filter and sort each list and then print them. Here is how it might be done.

    • Stream the list of lists.
    • then stream each individual list and:
    • then return that as a list
    • and combine those lists into another list.
    
    List<List<String>> sortedLists = list.stream()
            .map(lst -> lst.stream()
                    .filter(o -> o.startsWith("A"))
                    .sorted(Comparator.reverseOrder()).toList())
        .toList();
    for(List<String> lst : sortedLists) {
        System.out.println(lst);
    }
    

    prints (given your data).

    [Ann]
    [Andrew, Alex]
    [Adisson]
    

    If, on the other hand you want to combine the lists into one applying the same requirements, then:

    • stream the list of lists
    • flatMap them to put all of the list contents into a single stream.
    • then apply the filter and sort methods.
    • and collect into a list.
    List<String> sortedList = list.stream().flatMap(List::stream)
                 .filter(o->o.startsWith("A"))
                 .sorted(Comparator.reverseOrder())
                 .toList();
    
    for (String name : sortedList) {
        System.out.println(name);
    }
    

    prints

    Ann
    Andrew
    Alex
    Adisson