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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With