Skip to content
Advertisement

What would be the most efficient code of removing every key from a HashMap with the key value stored in an ArrayList? [closed]

Say I have an ArrayList with n elements and a HashMap with k elements, is there any faster way than just using a for loop and iterating through each key value of the HashMap?

Advertisement

Answer

Given a

Map<K, V> yourMap = ...;
Collection<K> yourKeys = ...;

you can simply do

yourMap.keySet().removeAll(yourKeys);

Note that keySet() won’t be much faster than writing a loop and calling remove manually (because that’s basically what it does internally), but it will be simpler to write and read.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement