简体   繁体   English

使用 Java 8 Stream API 从对象列表中收集列表

[英]Collecting lists from an object list using Java 8 Stream API

I have a class like this我有这样的课

public class Example {
    private List<Integer> ids;

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

If I have a list of objects of this class like this如果我有一个像这样的此类的对象列表

List<Example> examples;

How would I be able to map the id lists of all examples into one list?我如何能够将所有示例的 id 列表映射到一个列表中? I tried like this:我试过这样:

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

but getting an error with Collectors.toList()但是Collectors.toList()出现错误

What would be the correct way to achive this with Java 8 stream api?使用 Java 8 流 api 实现这一目标的正确方法是什么?

Use flatMap :使用flatMap

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

Another solution by using method reference expression instead of lambda expression:使用方法引用表达式而不是 lambda 表达式的另一种解决方案:

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

您可以使用 flatMap 替代 stream.map

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

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