我有两个实体:
我有一个Collection<Node>
,我正在尝试在一行代码中构建所有Set<Integer>
ID的Leaf
。我认为Stream
可能有可能,但直到现在,我只能这样点:
Set<Integer> leafIds = Sets.newHashSet();
root.getNodes()
.forEach(node -> node.getLeaves()
.forEach(leaf -> leafIds.add(leaf.getId())));
我不喜欢手动创建集合并使用方法Collection.add()
向其添加元素的部分(不是线程安全,危险且未优化)。我觉得有可能做类似的事情:
root.getNodes()
.stream()
.???
.getLeaves()
.map(Leaf::getId)
.distinct()
.collect(Collectors.toSet());
有什么想法吗?
答案 0 :(得分:3)
有可能。使用flatMap
,您可以从这些节点的所有叶片的Stream<Node>
到Stream<Leaf>
:
Set<Integer> leaves = root.getNodes().stream()
.flatMap (n -> n.getLeaves().stream())
.distinct()
.map(Leaf::getId)
.collect(Collectors.toSet());