Search code examples
javajava-stream

How could I properly Collect a Set<String> by using streams and map in this operation?


I think I can make this simplier but can not figure out how to properly use .map() here and then Collect to a Set, can you help?

I am using parallel stream so that this operation is done faster, each tree has nodes but I just want all their names without repeating (using Set)... The nodeName is composed of the id+version

My working code which correctly returns Set<String>:

// Set for not repeating node names between trees
NavigableSet<String> nodeNames = new ConcurrentSkipListSet<>();
trees.parallelStream().forEach(
        tree -> tree.getNodes().forEach(node -> nodeNames.add(node.getId() + node.getVersion())));

I was trying the following to achieve .map() usage:

trees.parallelStream()
            .map(tree -> tree.getNodes().stream().map(node -> node.getId() + node.getVersion()))
            .collect(Collectors.toSet());

But the collection returned is Set<Stream<String>>, I need Set<String>


Solution

  • Try this:

    trees.parallelStream()
      .flatMap(tree -> tree.getNodes().stream().map(node -> node.getId() + node.getVersion()))
      .collect(Collectors.toSet());
    

    That will flatten down the result from the map to have all results in one long Set rather than in a Set of Streams.