HashMap remove(Object) in Java

remove(Object): This method is available in java.util.HashMap class of Java.

Syntax:

V java.util.HashMap.remove(Object key)

This method takes one argument. This method removes the mapping for the specified key from this map if present.

Parameters: One parameter is required for this method.

key: key whose mapping is to be removed from the map.

Returns: the previous value associated with key, or null if there was no mapping for key.

Exceptions: NA

Approach

Java

import java.util.HashMap;

public class HashMapremove {
    public static void main(String[] args) {
        HashMap<String, Integer> hashMap =
new HashMap<String, Integer>();

        hashMap.put("Hello", 1);
        hashMap.put("World", 2);

        Object key = "Hello";
        hashMap.remove(key);

        System.out.println(hashMap);

    }
}

Output:

{World=2}


No comments:

Post a Comment