使用Java 8 Stream API从对象列表中收集列表 [英] Collecting lists from an object list using Java 8 Stream API
本文介绍了使用Java 8 Stream API从对象列表中收集列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的班
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;
如何将所有示例的ID列表映射到一个列表中? 我这样尝试过:
How would I be able to map the id lists of all examples into one list? I tried like this:
List<Integer> concat = examples.stream().map(Example::getIds).collect(Collectors.toList());
但出现Collectors.toList()
使用Java 8流api实现此目标的正确方法是什么?
What would be the correct way to achive this with Java 8 stream api?
推荐答案
使用flatMap
:
List<Integer> concat = examples.stream()
.flatMap(e -> e.getIds().stream())
.collect(Collectors.toList());
这篇关于使用Java 8 Stream API从对象列表中收集列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文