Wednesday, October 19, 2022

How to Remove Entry From HashMap in Java

In this post we'll see how to remove an entry (key, value pair) from Map. Options you have are as given below-

  1. Using remove method- remove(Object key) provided by Map. See Example
  2. Using another remove method variant- remove(Object key, Object value) provided by Map. See Example
  3. Using remove() method provided by iterator. See Example
  4. Using removeIf() method. See Example

So, let's see when to use which method and why.

Removing entry from HashMap using remove(Object key) method

If you know the key for the entry which has to be removed, it is convenient to use remove(Object key) method rather than iterating the Map and then use iterator.remove() to remove the entry. This method returns the value which was associated with the removed key or null if the map contained no mapping for the key.

Here is an example with the map of cities where we'll try to remove Map.entry by passing one of the key.

import java.util.HashMap;
import java.util.Map;

public class RemoveEntryDemo {

  public static void main(String[] args) {
    // Setting up a HashMap
    Map<String, String> cityMap = new HashMap<String, String>();
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Berlin");
    
    System.out.println("*** Map Initially ***");
    System.out.println(cityMap);
      
    cityMap.remove("4");
    System.out.println("*** Map After removal ***");
    System.out.println(cityMap);
  }
}

Output

*** Map Initially ***
{1=New York City, 2=New Delhi, 3=Mumbai, 4=Berlin}
*** Map After removal ***
{1=New York City, 2=New Delhi, 3=Mumbai}

As you can see the entry with key as "4" is removed from the HashMap.

Removing entry from HashMap using remove(Object key, Object value) method

This is another overloaded remove() method in Map which makes removing an entry more restrictive. This method removes the entry for the specified key only if it is currently mapped to the specified value.

public class RemoveEntryDemo {

  public static void main(String[] args) {
    // Setting up a HashMap
    Map<String, String> cityMap = new HashMap<String, String>();
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Berlin");
    
    System.out.println("*** Map Initially ***");
    System.out.println(cityMap);
      
    cityMap.remove("4", "Berlin");
    System.out.println("*** Map After removal ***");
    System.out.println(cityMap);
  }
}

Output

{1=New York City, 2=New Delhi, 3=Mumbai, 4=Berlin}
*** Map After removal ***
{1=New York City, 2=New Delhi, 3=Mumbai}

Since the passed key "4" is mapped to the specified value "Berlin" so entry is removed.

If you give a value that is not mapped with any key no entry is removed. For example, if you try cityMap.remove("4", "London"); HashMap will have no change.

Using iterator's remove() method

If you don't know the key before hand and iterating the Map to find the entry that has to be removed then using remove() method of the Iterator is a safe bet.

If you have to iterate a HashMap then you need to get a collection view of the Map. The iterators returned by HashMap's "collection view methods" are fail-fast: if the Map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. Here is an example where remove() method of the Map is used to remove an entry (Structural modification) rather than using the remove() method of the iterator. This operation results in ConcurrentModificationException being thrown.

public class RemoveEntryDemo {

  public static void main(String[] args) {
    // Setting up a HashMap
    Map<String, String> cityMap = new HashMap<String, String>();
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Berlin");
    
    System.out.println("*** Map Initially ***");
    System.out.println(cityMap);
    Iterator<Entry<String, String>> itr = cityMap.entrySet().iterator();
    while(itr.hasNext()) {
      String key = itr.next().getKey();
      if(key.equals("2")) {
        cityMap.remove(key);
      }
    }

    System.out.println("*** Map After removal ***");
    System.out.println(cityMap);
  }
}

Output

*** Map Initially ***
{1=New York City, 2=New Delhi, 3=Mumbai, 4=Berlin}
Exception in thread "main" java.util.ConcurrentModificationException
	at java.base/java.util.HashMap$HashIterator.nextNode(HashMap.java:1597)
	at java.base/java.util.HashMap$EntryIterator.next(HashMap.java:1630)
	at java.base/java.util.HashMap$EntryIterator.next(HashMap.java:1628)
	at com.netjstech.collections.RemoveEntryDemo.main(RemoveEntryDemo.java:23)

Correct way to remove an entry from a Map while iterating it is to use iterator's remove() method.

public class RemoveEntryDemo {

  public static void main(String[] args) {
    // Setting up a HashMap
    Map<String, String> cityMap = new HashMap<String, String>();
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Berlin");
    
    System.out.println("*** Map Initially ***");
    System.out.println(cityMap);
    Iterator<Entry<String, String>> itr = cityMap.entrySet().iterator();
    while(itr.hasNext()) {
      if(itr.next().getKey().equals("2")) {
        itr.remove();
      }
    }

    System.out.println("*** Map After removal ***");
    System.out.println(cityMap);
  }
}

Output

*** Map Initially ***
{1=New York City, 2=New Delhi, 3=Mumbai, 4=Berlin}
*** Map After removal ***
{1=New York City, 3=Mumbai, 4=Berlin}

Using removeIf() method

removeIf() method is in Collection interface, since Map doesn't implement Collection so removeIf() method is not directly accessible in HashMap but after getting the Collection view of a Map removeIf() method can be used.

public class RemoveEntryDemo {

  public static void main(String[] args) {
    // Setting up a HashMap
    Map<String, String> cityMap = new HashMap<String, String>();
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Berlin");
    
    System.out.println("*** Map Initially ***");
    System.out.println(cityMap);
    cityMap.entrySet().removeIf(entry -> entry.getKey().equals("2"));


    System.out.println("*** Map After removal ***");
    System.out.println(cityMap);
  }
}

Output

*** Map Initially ***
{1=New York City, 2=New Delhi, 3=Mumbai, 4=Berlin}
*** Map After removal ***
{1=New York City, 3=Mumbai, 4=Berlin}
If you have a collection view of values then
cityMap.values().removeIf(v -> v.equals("Mumbai"));
Same way if you have a collection view of keys
cityMap.keySet().removeIf(k -> k.equals("2"));

That's all for this topic How to Remove Entry From HashMap in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Java Map putIfAbsent() With Examples
  2. Java Map containsValue() - Check if Value Exists in Map
  3. How to Sort a HashMap in Java
  4. How LinkedList Class Works Internally in Java
  5. How to Sort Elements in Different Order in TreeSet

You may also like-

  1. Difference Between HashMap And ConcurrentHashMap in Java
  2. CompletableFuture in Java With Examples
  3. super Keyword in Java With Examples
  4. strictfp in Java
  5. Angular Application Bootstrap Process
  6. ServiceLocatorFactoryBean in Spring
  7. Spring @Async @EnableAsync Annotations - Asynchronous Method Support
  8. Python Conditional Statement - if, elif, else Statements

No comments:

Post a Comment