我有 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
andclear
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/