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
and clear
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!