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

时间:2020-02-17 08:53:11

标签: java algorithm data-structures

让我们考虑以下两个哈希图:

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

谢谢。

3 个答案:

答案 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

演示https://onlinegdb.com/SJdcpbOXU

答案 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);
    }
    }

谢谢。