In Java, you can use the removeIf()
method to remove elements from a Set
-based in a certain condition. Here’s how you can do it:
- First, get the entry set from the map. The entry set is a
Set<Map.Entry<K,V>>
. - Then, call
removeIf()
on this set. - The
removeIf()
method takes a predicate, which is a condition that is checked against every element in the set. - If the predicate is
true
for a given element, that element is removed.
Here is the Java code:
package org.kodejava.util;
import java.util.HashMap;
import java.util.Map;
public class MapEntrySetRemoveIf {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
map.put("Four", 4);
// Remove entry with key "Two"
map.entrySet().removeIf(entry -> entry.getKey().equals("Two"));
map.entrySet().forEach(System.out::println);
}
}
Output:
One=1
Four=4
Three=3
This will remove the map entry with “Two” as its key. You can replace entry.getKey().equals("Two")
with any condition you desire.
Please note that this operation may throw ConcurrentModificationException
if the map is structurally modified at any time after the iterator is created. Make sure you’re aware of concurrent modifications when using this method.
Latest posts by Wayan (see all)
- How do I use Proxy class to configure HTTP and SOCKS proxies in Java? - March 27, 2025
- How do I retrieve network interface information using NetworkInterface in Java? - March 26, 2025
- How do I work with InetAddress to resolve IP addresses in Java? - March 25, 2025