简体   繁体   English

如何使用 Stream API 对列表进行排序?

[英]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.我想输出以字母“A”开头的所有名称,并使用 Stream API 按字母倒序对它们进行排序。 The result should look like this: Ann, Andrew, Alex, Adisson.结果应如下所示: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.由于您将结果分配给List<List<String>> ,因此您似乎想要过滤和排序每个列表,然后打印它们。 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. flatMap 将所有列表内容放入单个流中。
  • 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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