I created two maps in Java that contain the same type of Keys and Values:
Map<Position,Movement> A;
Map<Position,Movement> B;
I want to remove from them both (not create a new Map) the keys that are the same. I don't care if the value is different or not. For example, if A
has Position: a2
, Movement: n,n
and B
has Position: a2
, Movement: 1,2
those entries should be removed.
I wonder if there is a fast way to do that without iterating the shortest map and compare every single key.
Thanks
You can use an Iterator
on the keySet()
of one of the maps and remove the element from the iterator and the other map if the key is present in the other map.
Iterator<String> itr = map1.keySet().iterator();
String key;
while (itr.hasNext()) {
key = itr.next();
if (map2.containsKey(key)) {
itr.remove();
map2.remove(key);
}
}
Demo:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, String> map1 = new HashMap<String, String>();
map1.put("a", "1");
map1.put("b", "1");
map1.put("x", "1");
map1.put("c", "1");
map1.put("z", "1");
map1.put("d", "1");
Map<String, String> map2 = new HashMap<String, String>();
map2.put("w", "1");
map2.put("x", "1");
map2.put("b", "1");
map2.put("y", "1");
map2.put("c", "1");
map2.put("z", "1");
Iterator<String> itr = map1.keySet().iterator();
String key;
while (itr.hasNext()) {
key = itr.next();
if (map2.containsKey(key)) {
itr.remove();
map2.remove(key);
}
}
System.out.println(map1);
System.out.println(map2);
}
}
Output:
{a=1, d=1}
{w=1, y=1}
Solution using Stream
:
map1.keySet()
.stream()
.filter(k -> map2.containsKey(k))
.collect(Collectors.toList())
.forEach(k -> {
map1.remove(k);
map2.remove(k);
});
Given below is a compact version (Thanks to Holger) of the first solution:
for (Iterator<String> itr = map1.keySet().iterator(); itr.hasNext();) {
if (map2.keySet().remove(itr.next())) {
itr.remove();
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments