TreeMap getOrDefault(Object, String) in Java

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

Syntax:

String java.util.Map.getOrDefault(Object key, String 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 in appropriate type for this map.

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

Approach 1: When no exception

Java

import java.util.TreeMap;

public class TreeMapgetOrDefault {
    public static void main(String[] args) {

        TreeMap<Integer, String> treeMap =
new TreeMap<Integer, String>();

        treeMap.put(2, "Hello");
        treeMap.put(11, "Java");
        treeMap.put(23, "Program");
        treeMap.put(6, "C++");
        treeMap.put(25, "Program");

        Object key = 1;
        String defaultValue = "Spring";

        System.out.println(treeMap.getOrDefault(key,
defaultValue));

    }
}

Output:

Spring


Approach 2: NullPointerException 

Java

import java.util.TreeMap;

public class TreeMapgetOrDefault {
    public static void main(String[] args) {

        TreeMap<Integer, String> treeMap =
new TreeMap<Integer, String>();

        treeMap.put(2, "Hello");
        treeMap.put(11, "Java");
        treeMap.put(23, "Program");
        treeMap.put(6, "C++");
        treeMap.put(25, "Program");

        Object key = null;
        String defaultValue = "Spring";

        System.out.println(treeMap.getOrDefault(key,
defaultValue));

    }
}

Output:

Exception in thread "main" java.lang.NullPointerException at java.base/java.util.Objects.requireNonNull(Objects.java:208) at java.base/java.util.TreeMap.getEntry(TreeMap.java:345) at java.base/java.util.TreeMap.get(TreeMap.java:279) at java.base/java.util.Map.getOrDefault(Map.java:619)


No comments:

Post a Comment