gpt4 book ai didi

Java:如果值使用流匹配,则组合两个映射键

转载 作者:行者123 更新时间:2023-11-29 08:20:25 24 4
gpt4 key购买 nike

我有两张 map

map 1:{123, "aaa"}, {234, "bbb"}

map 2:{345, "ccc"}, {456, "aaa"}

使用流,我想遍历这些 map 并返回{123, 456}

我试过类似的东西

map1.entrySet().stream()
.filter(node ->
map2.entrySet().stream().anyMatch(
newNode -> node.getValue().equals(newNode.getValue()))
.collect(...);

但这只给我第一张 map 的列表。有什么想法吗?

最佳答案

放弃这在流中很容易完成的想法,而只是迭代。

基本上 - 如果您有匹配项,则需要添加两个键。使用 collect 运算符,您正在执行一项离散操作,但您确实想要执行多项操作。

所以...只需迭代即可。

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;
}

关于Java:如果值使用流匹配,则组合两个映射键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59400205/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com