java - 在 2 个 HashMap 中找到不同的值

标签 java hashmap

我有 2 个包含数百万条记录的 HashMap。为简单起见,我将只处理少数记录。我想找到 map a 中不在 map b 中的值。有这样做的功能吗?最快的方法是什么?

Map a = new HashMap();
a.put(1, "big");
a.put(2, "hello");
a.put(3, "world");

Map b = new HashMap();

b.put(1,"hello");
b.put(2, "world");

在这种情况下,输出应该是 "big",因为它在 a 中,而不是在 b 中。

最佳答案

您正在寻找对 map 值的 removeAll 操作。

public static void main(String[] args) {
    Map<Integer, String> a = new HashMap<>();
    a.put(1, "big");
    a.put(2, "hello");
    a.put(3, "world");

    Map<Integer, String> b = new HashMap<>();
    b.put(1,"hello");
    b.put(2, "world");

    a.values().removeAll(b.values()); // removes all the entries of a that are in b

    System.out.println(a); // prints "{1=big}"
}

values()返回此映射中包含的值的 View :

Returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa.

因此,从值中删除元素会有效地删除条目。这也记录在案:

The collection supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Collection.remove, removeAll, retainAll and clear operations.


这会就地从 map 中移除。如果您想要一个包含结果的新 map ,您应该在一个新的 map 实例上调用该方法。

Map<Integer, String> newMap = new HashMap<>(a);
newMap.values().removeAll(b.values());

旁注:don't use raw types !

关于java - 在 2 个 HashMap 中找到不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35064018/

相关文章:

java - 什么时候包含什么?

对象引用的 Java 哈希表问题

java - 如何在 Java 中同步 Map <-> MySQL?

algorithm - 使用哈希表解决两个和问题时如何考虑重复值?

java - 什么是NullPointerException,我该如何解决?

java - 在 Apache Spark 中解析 JSON 时出现奇怪的错误

java - 如何获取tomcat日志输出?

java - 如何使用 Java 调试接口(interface)跟踪递归调用?

java - 用 Java 中的属性文件中的值替换 HashMap 键

java - 根据字符串键中的标记对 JAVA 映射键进行分组