我有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");在这种情况下,输出应该是"big",因为它是在a中而不是在b中。
发布于 2016-01-28 14:24:11
您正在寻找映射值上的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()返回此映射中包含的值的视图:
返回此映射中包含的值的
Collection视图。集合由映射支持,因此对映射的更改反映在集合中,反之亦然。
因此,从值中删除元素可以有效地删除条目。这也是记录在案的:
集合支持元素删除,它通过
Iterator.remove、Collection.remove、removeAll、retainAll和clear操作从映射中删除对应的映射。
这会从地图上移除。如果您想要一个带有结果的新映射,您应该在一个新的map实例上调用该方法。
Map<Integer, String> newMap = new HashMap<>(a);
newMap.values().removeAll(b.values());备注:不要使用原始类型!
发布于 2016-01-28 14:29:13
@Tunaki的解决方案工作得很好,可读性很强,而且很短。
为了完整起见,“手工”解决方案:
for (String s : a.values()) {
    if (!b.containsValue(s)) {
        System.out.println (s);
        // process the value (e.g. add it to a list for further processing)
    }
}发布于 2016-01-28 14:29:15
如果允许您使用4,则可以使用SetUtils.difference(),它的性能可能与@Tunaki的回答类似。
https://stackoverflow.com/questions/35064018
复制相似问题