Home > Mobile >  What would be the most efficient code of removing every key from a HashMap with the key value stored
What would be the most efficient code of removing every key from a HashMap with the key value stored

Time:05-03

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?

CodePudding user response:

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.

CodePudding user response:

If I understand your question, your ArrayList contains values & you want to remove keys which are mapped to values of ArrayList :

        Map<String, String> map=new HashMap<String, String>();
        map.put("A", "Val1");
        map.put("B", "Val2");
        map.put("C", "Val3");
        map.put("D", "Val4");
        List<String> list=new ArrayList<String>();
        ll.add("Val1");
        ll.add("Val2");
        System.out.println(map);
        map.values().removeAll(list);
        System.out.println(map);
  •  Tags:  
  • java
  • Related