You may use something like this:
List<String> commonValues = myMap.values().stream()
.reduce((a, b) -> {
a.retainAll(b);
return a;
})
.orElse(Collections.emptyList());
From the doc of retainAll
:
Retains only the elements in this collection that are contained in the specified collection (optional operation). In other words, removes from this collection all of its elements that are not contained in the specified collection.
In case you're working with multiple threads or collections which are immutable:
List<String> commonValues = myMap.values().stream()
.reduce((a, b) -> {
List<String> c = new ArrayList<>(a);
c.retainAll(b);
return c;
})
.orElse(Collections.emptyList());
Though this solution creates a new copy every iteration.
Another way would be somewhat more hacky:
List<String> commonValues = myMap.values().stream()
.reduce(null, (a, b) -> {
if(a == null) return new ArrayList<>(b);
a.retainAll(b);
return a;
});
But this time, commonValues
may be null
, so you'd have to check for that