Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to aggregate map values into set using streams

Is there some easy way how to convert Map<Key, List<Value>> into Set<Value> to get a set of all unique elements nested int the map? I know this should be possible using reduce or flatmap but I am struggling with the right combination.

I know I could do this using for loop but I would like to perform this operation using streams.

like image 718
Smajl Avatar asked Nov 16 '25 09:11

Smajl


1 Answers

Set<Value> set = map.values().stream()
                             .flatMap(List::stream)
                             .collect(Collectors.toSet());

Set will not add a Value that is already in it, so you have to make sure, that your Value objects have a proper equals() method.


Edit: List::stream is equivalent to list -> list.stream() in functionality according to this post.

like image 184
Sorin Avatar answered Nov 18 '25 23:11

Sorin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!