I have two maps
Map 1: {123, "aaa"}, {234, "bbb"}
Map 2: {345, "ccc"}, {456, "aaa"}
Using streams, I would like to go through these maps and return {123, 456}
I've tried something like
map1.entrySet().stream()
.filter(node ->
map2.entrySet().stream().anyMatch(
newNode -> node.getValue().equals(newNode.getValue()))
.collect(...);
But that only gives me the the list of the first map. Any ideas?
Abandon the idea that this is something that's easily done in streams, and just iterate across.
Basically - if you have a match, you need to add both keys. With the collect
operator, you're doing one discrete operation and you really want to do more than one.
So...just iterate instead.
public static <K, V> Collection<K> findKeysOfEqualValues(Map<K, V> map1, Map<K, V> map2) {
Set<K> keyList = new LinkedHashSet<>();
for(Map.Entry<K, V> mapEntry1 : map1.entrySet()) {
for(Map.Entry<K, V> mapEntry2 : map2.entrySet()) {
if(Objects.equals(mapEntry1.getValue(), mapEntry2.getValue())) {
keyList.add(mapEntry1.getKey());
keyList.add(mapEntry2.getKey());
}
}
}
return keyList;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.