使用Java 8在一行中构建一组Node.Leaf.Id

时间:2014-10-21 09:29:38

标签: java java-8

我有两个实体:

  • 包含树叶的节点。

我有一个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());

有什么想法吗?

1 个答案:

答案 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());