简体   繁体   中英

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM