【问题标题】:Collecting lists from an object list using Java 8 Stream API使用 Java 8 Stream API 从对象列表中收集列表
【发布时间】:2017-09-26 16:27:00
【问题描述】:

我有这样的课

public class Example {
    private List<Integer> ids;

    public getIds() {
        return this.ids; 
    }
}

如果我有这样的此类的对象列表

List<Example> examples;

如何将所有示例的 id 列表映射到一个列表中? 我试过这样:

List<Integer> concat = examples.stream().map(Example::getIds).collect(Collectors.toList());

Collectors.toList() 出现错误

使用 Java 8 流 api 实现这一目标的正确方法是什么?

【问题讨论】:

标签: java java-8


【解决方案1】:

使用flatMap:

List<Integer> concat = examples.stream()
    .flatMap(e -> e.getIds().stream())
    .collect(Collectors.toList());

【讨论】:

  • 你能解释一下flatMapmap之间的区别
  • @CraigR8806 详尽的解释here
  • 如果e.getIds()返回一个空列表或null会发生什么?对空列表或 null 的测试如何包含在语句中?
  • @gabriel "empty list" 好吧,列表中没有任何内容,但它的工作原理是一样的。 “空”NullPointerException 将被抛出。你想如何处理 null;为什么要(特别)处理一个空列表?
  • 你可以做类似{ List&lt;Integer&gt; ids = e.getIds(); if (ids == null) ids = Collections.emptyList(); return ids.stream(); }的事情。但是考虑到 null 本身可能是一个错误;所以最好修复它而不是解决它。
【解决方案2】:

使用方法引用表达式代替 lambda 表达式的另一种解决方案:

List<Integer> concat = examples.stream()
                               .map(Example::getIds)
                               .flatMap(List::stream)
                               .collect(Collectors.toList());

【讨论】:

    猜你喜欢
    • 2019-04-19
    • 1970-01-01
    • 2019-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多