TreeMap putAll(Map) in Java

putAll(Map): This method is available in java.util.TreeMap class of Java.

Syntax:

void java.util.TreeMap.putAll(Map<? extends K, ? extends V> map)

This method takes one argument. This method copies all of the mappings from the specified map to this map. These mappings replace any mappings that this map had for any of the keys currently in the specified map.

Parameters: One parameter is required for this method.

map: mappings to be stored in this map.

Throws:

1. ClassCastException - if the class of a key or value in the specified map prevents it from being stored in this map.

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

Approach 1: When no exception

Java

import java.util.TreeMap;

public class TreeMapputAll {
    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");

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

        treeMap2.putAll(treeMap);
        System.out.println(treeMap2);

    }
}

Output:

{2=Hello, 6=C++, 11=Java, 23=Program, 25=Program}


Approach 2: NullPointerException 

Java

import java.util.TreeMap;

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

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

        treeMap2.putAll(treeMap);
        System.out.println(treeMap2);

    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.Map.size()" because "map" is null at java.base/java.util.TreeMap.putAll(TreeMap.java:314)


No comments:

Post a Comment