IdentityHashMap getOrDefault(Object, V) in Java

getOrDefault(Object, V): This method is available in java.util.IdentityHashMap class of Java.

Syntax:

V java.util.Map.getOrDefault(Object key, V defaultValue)

This method takes two arguments. This method returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.

Parameters: Two parameters are required for this method.

key: the key whose associated value is to be returned.

defaultValue: the default mapping of the key.

Returns: the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.

Throws:

1. ClassCastException - if the key is of an inappropriate type for this map.

2. NullPointerException - if the specified key is null and this map does not permit null keys.

Approach

Java

import java.util.IdentityHashMap;

public class IdentityHashMapgetOrDefault {

    public static void main(String args[]) {

        IdentityHashMap<String, Integer> identityHashMap =
new IdentityHashMap<String, Integer>();

        identityHashMap.put("Java", 1);
        identityHashMap.put("Hello", 2);

        Object key = "C++";
        Integer defaultValue = 10;
        System.out.println(identityHashMap.getOrDefault(key,
defaultValue));

    }

}

Output:

10

No comments:

Post a Comment