Press "Enter" to skip to content

HashMap putAll() Method in Java

The putAll() method of HashMap copies all the entries of the specified map into this map. It throws NullPointerException if the specified map is null, or if this map does not permit null keys or values, and the specified map contains null keys or values.

Syntax

void putAll(Map<K,V> map)

Parameters

The map we want to copy
Freshers Placement

Program

import java.util.HashMap;
import java.util.Map;

public class HashMapPutAllExample {

	public static void main(String[] args) {

		Map<Integer, String> alphabates = new HashMap<>();
		Map<Integer, String> vowels = new HashMap<>();
		alphabates.put(21, "G");
		alphabates.put(19, "F");
		alphabates.put(13, "C");
		alphabates.put(24, "D");

		vowels.put(1, "A");
		vowels.put(2, "E");
		vowels.put(3, "I");
		vowels.put(4, "O");
		vowels.put(5, "U");
		System.out.println("Elements of alaphabates map: " + alphabates);
		System.out.println("Elements of vowels map: " + vowels);
		alphabates.putAll(vowels);
		System.out.println("Elements of alphabates after adding all elements of vowels: " + alphabates);

	}
}

Output

Elements of alaphabates map: {19=F, 21=G, 24=D, 13=C}
Elements of vowels map: {1=A, 2=E, 3=I, 4=O, 5=U}
Elements of alphabates after adding all elements of vowels: {1=A, 2=E, 19=F, 3=I, 4=O, 21=G, 5=U, 24=D, 13=C}

Comments are closed.