Let's say I've a HashMap
which contains key as a String
and value as a Set
of Integer
s (Map<String, Set<Integer>>
).
And say that the map is populated with following values:
Map<String, Set<Integer>> map = new HashMap<>();
map.put("w1", Set.of(1,3,4,6,7));
map.put("w2", Set.of(2,3,4,5,7));
map.put("w3", Set.of(1,2,3,5,7));
How can I find common set of values across all keys using Streams in Java? e.g.: In this case, the common set of values across all keys is Set.of(3,7)
.
First note that using stream is not always the cleanest way.
My idea would be to get the first set and iterate over the rest to check if all of them contain it:
Set<Integer> res = map.values().iterator().next().stream()
.filter(item -> map.values().stream().allMatch(set -> set.contains(item)))
.collect(Collectors.toSet());
This is a concise solution but it checks the first set twice. You can also add a check to see if the map contains any entries.