哈希图.查找两个哈希映射之间具有相同值的键



让我们考虑我们有两个哈希图,如下所示:

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"。

谢谢。

按值分组并将键存储在列表中:

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()));

您可以提高时间复杂度,以O(n + m)其中n是第一个地图的大小,m是第二个地图的大小。

  • 我们可以通过将values作为键,keys作为值来实现这一点。
  • 步骤:
    • 遍历每张地图。
    • 将所有当前映射值存储在新映射
    • 中,并在列表中收集具有该值的所有键,并将具有此列表的当前值放入新映射中。
    • 现在,循环访问任何新的地图集合并获取公用键及其各自的打印值。

片段:

private static void showCommonValueKeys(HashMap<String, Integer> map1,HashMap<String, Integer> map2){
Map<Integer,List<String>> map1Collect = flipKeyValue(map1);
Map<Integer,List<String>> map2Collect = flipKeyValue(map2);
for(Map.Entry<Integer,List<String>> m : map1Collect.entrySet()){
int key = m.getKey();
if(map2Collect.containsKey(key)){
System.out.println("For value " + key);
System.out.println("First map keys: " + m.getValue().toString());
System.out.println("Second map keys: " + map2Collect.get(key).toString());
System.out.println();
}
}
}
private static  Map<Integer,List<String>> flipKeyValue(HashMap<String, Integer> map){
Map<Integer,List<String>> mapCollect = new HashMap<>(); 
for(Map.Entry<String,Integer> m : map.entrySet()){
String  key = m.getKey();
int val = m.getValue();
mapCollect.putIfAbsent(val,new ArrayList<>());
mapCollect.get(val).add(key);
}
return mapCollect;
}

演示:https://onlinegdb.com/SJdcpbOXU

这可以通过两个复杂度为 n*m 的 for 循环来实现,其中 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);
}
}

谢谢。

最新更新