让我们考虑以下两个哈希图:
HashMap<String, Integer> map1 = new HashMap<>();
map1.put("vishal", 10);
map1.put("sachin", 30);
map1.put("vaibhav", 20);
HashMap<String, Integer> map2 = new HashMap<>();
map2.put("Raja", 10);
map2.put("John", 30);
map2.put("Krishna", 20);
map1中的“ vaibhav”和map2中的“ krishna”具有相同的值。
我需要从两个映射中找到具有相同值的键。在这种情况下,“ vaibhav”和“ Krishna”。
谢谢。
答案 0 :(得分:3)
按值分组并将密钥存储在列表中
Stream.of(map1.entrySet(), map2.entrySet())
.flatMap(Collection::stream)
.collect(Collectors.groupingBy(
Map.Entry::getValue,
Collectors.mapping(
Map.Entry::getKey,
Collectors.toList()
)
));
它将创建:
{20=[vaibhav, Krishna], 10=[vishal, Raja], 30=[sachin, John]}
其他方法
Map<Integer, List<String>> collect = new HashMap<>();
map1.entrySet().forEach(e -> collect
.computeIfAbsent(e.getValue(), k -> new ArrayList<>())
.add(e.getKey()));
map2.entrySet().forEach(e -> collect
.computeIfAbsent(e.getValue(), k -> new ArrayList<>())
.add(e.getKey()));
答案 1 :(得分:1)
您可以将时间复杂度提高到...
return render.index(greeting)
...
,其中O(n + m)
是第一张地图的大小,n
是第二张地图的大小。
m
用作键并将values
用作值来实现此目的。 代码段:
keys
答案 2 :(得分:0)
这可以通过两个for循环来实现,其复杂度为n * m,其中n.m是每个图的大小。
Map<String, String> map1 = new HashMap<>();
map1.put("santhosh", "1");
map1.put("raja", "2");
map1.put("arun", "3");
Map<String, String> map2 = new HashMap<>();
map2.put("kumar", "1");
map2.put("mani", "1");
map2.put("tony", "3");
for (Map.Entry<String, String> entry1 : map1.entrySet()) {
String key1 = entry1.getKey();
String value1 = entry1.getValue();
for (Map.Entry<String, String> entry2 : map2.entrySet()) {
String key2 = entry2.getKey();
String value2 = entry2.getValue();
if (value1 == value2) {
System.out.println(key1 + " " + key2);
}
}
谢谢。