Java 8 Stream Collecting Set

JavaJava 8Java Stream

Java Problem Overview


To better understand the new stream API I'm trying to convert some old code, but I'm stuck on this one.

 public Collection<? extends File> asDestSet() {
    HashMap<IFileSourceInfo, Set<File>> map = new HashMap<IFileSourceInfo, Set<File>>();
    //...
    Set<File> result = new HashSet<File>();
    for (Set<File> v : map.values()) {
        result.addAll(v);
    }
    return result;
}

I can't seem to create a valid Collector for it:

 public Collection<? extends File> asDestSet() {
    HashMap<IFileSourceInfo, Set<File>> map = new HashMap<IFileSourceInfo, Set<File>>();
    //...
	return map.values().stream().collect(/* what? */);
}

Java Solutions


Solution 1 - Java

Use flatMap:

return map.values().stream().flatMap(Set::stream).collect(Collectors.toSet());

The flatMap flattens all of your sets into single stream.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmolokView Question on Stackoverflow
Solution 1 - JavaTagir ValeevView Answer on Stackoverflow