LinkedHashMap getOrDefault(Object, V) in Java

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

Syntax:

V java.util.LinkedHashMap.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.

Exceptions: NA

Approach

Java

import java.util.LinkedHashMap;

public class LinkedHashMapgetOrDefault {

    public static void main(String args[]) {

        LinkedHashMap<String, Integer> linkedHashMap =
new LinkedHashMap<String, Integer>();

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

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

    }

}

Output:

10


No comments:

Post a Comment