在2个HashMaps中查找不同的值

Jan*_*wan 4 java hashmap

我有2个HashMaps,有数百万条记录.为简单起见,我将只处理几条记录.我想找到地图a中不在地图中的值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");
Run Code Online (Sandbox Code Playgroud)

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

Tun*_*aki 10

您正在寻找对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}"
}
Run Code Online (Sandbox Code Playgroud)

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

返回Collection此映射中包含的值的视图.该集合由地图支持,因此对地图的更改将反映在集合中,反之亦然.

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

该collection支持元素移除,即从映射中相应的映射,经由Iterator.remove,Collection.remove,removeAll,retainAllclear操作.


这将从地图中删除.如果要创建包含结果的新映射,则应在新映射实例上调用该方法.

Map<Integer, String> newMap = new HashMap<>(a);
newMap.values().removeAll(b.values());
Run Code Online (Sandbox Code Playgroud)

旁注:不要使用原始类型!