HashMap remove(Object, Object) in Java

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

Syntax:

boolean java.util.HashMap.remove(Object key, Object value)

This method takes two arguments. This method removes the entry for the specified key only if it is currently mapped to the specified value.

Parameters: Two parameters are required for this method.

key: key with which the specified value is associated.

value: value expected to be associated with the specified key.

Returns: true if the value was removed

Approach

Java

import java.util.HashMap;

public class HashMapremove2 {
    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";
        Object value = 1;
        hashMap.remove(key, value);

        System.out.println(hashMap);

    }
}

Output:

{World=2}


No comments:

Post a Comment