Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Stream Collecting Set

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? */); } 
like image 446
molok Avatar asked May 26 '15 17:05

molok


People also ask

Can you Stream a set Java?

Being a type of Collection, we can convert a set to Stream using its stream() method.

What does collect () do in Java?

Java Stream collect() is mostly used to collect the stream elements to a collection. It's a terminal operation. It takes care of synchronization when used with a parallel stream. The Collectors class provides a lot of Collector implementation to help us out.

How do you collect data from a Stream?

Gather all the stream's items in the collection created by the provided supplier. Count the number of items in the stream. Sum the values of an Integer property of the items in the stream. Calculate the average value of an Integer property of the items in the stream.


1 Answers

Use flatMap:

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

The flatMap flattens all of your sets into single stream.

like image 135
Tagir Valeev Avatar answered Sep 22 '22 17:09

Tagir Valeev