Removing Multiple Elements from Java Maps

Removing Multiple Elements from Java Maps

Java Maps store key-value pairs. There are scenarios where multiple entries must be removed simultaneous, either based on conditions or by specifying keys. This section demonstrates techniques for bulk removal in Java Maps.

Removing a Single Entry

Use the remove method to delete a single entry by its key:

Map<String, Integer> dataMap = new HashMap<>();
dataMap.put("Key1", 10);
dataMap.put("Key2", 20);
dataMap.remove("Key1");
System.out.println(dataMap); // Output: {Key2=20}

The example removes the entry with key "Key1", leaving only "Key2=20".

Removing Multiple Entreis

Conditional Removal

Use an iterator to traverse and remove entries meeting specific criteria:

Map<String, Integer> dataMap = new HashMap<>();
dataMap.put("Alpha", 5);
dataMap.put("Beta", 15);
dataMap.put("Gamma", 25);

Iterator<Map.Entry<String, Integer>> iter = dataMap.entrySet().iterator();
while (iter.hasNext()) {
    Map.Entry<String, Integer> e = iter.next();
    if (e.getValue() < 20) {
        iter.remove();
    }
}
System.out.println(dataMap); // Output: {Gamma=25}

This removes entries with values below 20, retaining only "Gamma=25".

Bulk Removal by Key Set

Remove multiple entries by creating a set of target keys and applying removeAll:

Map<String, Integer> dataMap = new HashMap<>();
dataMap.put("First", 100);
dataMap.put("Second", 200);
dataMap.put("Third", 300);

Set<String> removalKeys = new HashSet<>(Arrays.asList("First", "Second"));
dataMap.keySet().removeAll(removalKeys);
System.out.println(dataMap); // Output: {Third=300}

Entries with keys "First" and "Second" are removed, leaving "Third=300".

Tags: java Collections Map hashmap iterator

Posted on Tue, 19 May 2026 20:32:36 +0000 by davids701124