Find different values ​​in 2 HashMaps

I have 2 HashMaps with millions of entries. For simplicity, I will deal with several entries. I want to find values ​​that are on the map a, which are not in the map b. Is there a function for this? What is the fastest way to do this?

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");

In this case, the conclusion should be "big", since it is in a, not in b.

+4
source share
6 answers

You are looking for an operation removeAllfor map values.

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() returns a representation of the values ​​contained on this map:

Collection , . , .

, . :

, Iterator.remove, Collection.remove, removeAll, retainAll clear.


. , .

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

: !

+10

@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)
    }
}
+2

Apache Commons 4, SetUtils.difference(), , , @ .

+2

, :

Map<Integer, String> a = ...;
Map<Integer, String> b = ...;
Set<String> bVal = new HashSet<String>(b.values());
String[] res = a.values()
    .stream()
    .filter(s -> bVal.contains(s))
    .toArray(String[]::new);

res , . .

, . , , b .

-

+1
0
source

I assume that the unique values ​​u want do not depend on the key position (2, "hello" and 1, "hello")

This line should do only one line.

a.values().removeAll(b.values());

Warning: this removes all duplicate values ​​from 'a' hashmap

0
source

Source: https://habr.com/ru/post/1626364/


All Articles