What is AbstractMap putAll in Java?

AbstractMap.putAll() is a method of the Java AbstractMap class. We use it to copy all the mappings from a specified AbstractMap to another AbstractMap.

The behaviour of this putAll() operation is undefined if the specified AbstractMap is modified while the operation is in progress.

Syntax

AbstractMap.putAll(anExistingAbstractMap);

Parameters

The AbstractMap.putAll() method takes one parameter, the existingAbstractMap, to be copied.

Throws

The method throws:

  • UnsupportedOperationException when the putAll() operation is not supported by the other AbstractMap.

  • ClassCastException when the class of a key or value in the specified AbstractMap prevents it from being stored in the other AbstractMap.

  • NullPointerException if the specified AbstractMap is NULL, or if the other AbstractMap does not permit NULL keys or values, and the specified AbstractMap contains NULL keys or values.

  • IllegalArgumentException if some property of a key or value in the specified AbstractMap prevents it from being stored in the other AbstractMap.

AbstractMapDemo.java Illustration
AbstractMapDemo.java Illustration

Code

We can write the illustration above in the code snippet shown below.

import java.util.*;
class AbstractMapDemo {
public static void main(String[] args)
{
// Creating an AbstractMap
AbstractMap<Integer, String>
abstractMap = new HashMap<Integer, String>();
// Mapping string values to int keys
abstractMap.put(21, "Shot");
abstractMap.put(42, "Java");
abstractMap.put(34, "Yaaaayy");
// Printing the AbstractMap
System.out.println("The Mappings are: "
+ abstractMap);
// Creating a new AbstractMap
AbstractMap<Integer, String>
newAbstractMap = new HashMap<Integer, String>();
// Copying all the mappings
newAbstractMap.putAll(abstractMap);
// Printing the new AbstractMap
System.out.println("The new AbstractMap will be: "
+ newAbstractMap );
}
}