I have 2 HashMaps with millions of records. For simplicity, I will deal with only few records. I want to find the values which are in map a
that are not in map b
. Is there a function to do this? What's the quickest way to go about it?
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, output should be "big"
since it is in a
and not in b
.
You are looking for the removeAll
operation on the values of the map.
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 view of the values contained in this map:
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.
So removing elements from the values effectively removes the entries. This is also documented:
The collection supports element removal, which removes the corresponding mapping from the map, via the
Iterator.remove
,Collection.remove
,removeAll
,retainAll
andclear
operations.
This removes from the map in-place. If you want to have a new map with the result, you should call that method on a new map instance.
Map<Integer, String> newMap = new HashMap<>(a);
newMap.values().removeAll(b.values());
Side-note: don't use raw types!
The solution of @Tunaki will work fine, is readable and short.
Just for the sake of completeness the solution "by hand":
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With