使用 Java 8 Stream API 从对象列表中收集列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43682120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Collecting lists from an object list using Java 8 Stream API
提问by Jakob Abfalter
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? I tried like this:
我如何能够将所有示例的 id 列表映射到一个列表中?我试过这样:
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 实现此目标的正确方法是什么?
采纳答案by Andy Turner
Use flatMap
:
使用flatMap
:
List<Integer> concat = examples.stream()
.flatMap(e -> e.getIds().stream())
.collect(Collectors.toList());
回答by holi-java
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());