Create set Node.Leaf.Id in one line with Java 8

I have 2 objects:

  • Leaves
  • Nodes containing sheets.

I have Collection<Node>

and I am trying to plot Set<Integer>

all Leaf

ids in one line of code. I feel like it is possible with Stream

, but so far I can only calculate it like this:

Set<Integer> leafIds = Sets.newHashSet();
root.getNodes()
    .forEach(node -> node.getLeaves()
              .forEach(leaf -> leafIds.add(leaf.getId())));

      

I don't like the part where I manually create the collection and add items to it using a method Collection.add()

(not thread safe, dangerous and not optimized). I feel like it is possible to do something like:

root.getNodes()
  .stream()
  .???
  .getLeaves()
  .map(Leaf::getId)
  .distinct()
  .collect(Collectors.toSet());

      

Any idea?

+3


source to share


1 answer


It is possible. With flatMap

you can get from Stream<Node>

to Stream<Leaf>

all sheets of these nodes:



Set<Integer> leaves = root.getNodes().stream()
                          .flatMap (n -> n.getLeaves().stream())
                          .distinct()
                          .map(Leaf::getId)
                          .collect(Collectors.toSet());

      

+3


source







All Articles