Java HashMap putAll()

The syntax of the putAll() method is:

hashmap.putAll(Map m)

Here, hashmap is an object of the HashMap class.


putAll() Parameters

The putAll() method takes a single parameter.

  • map - map that contains mappings to be inserted into the hashmap

putAll() Return Value

The putAll() method does not return any values.


Example 1: Java HashMap putAll()

import java.util.HashMap;

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

    // create an HashMap
    HashMap<String, Integer> primeNumbers = new HashMap<>();

    // add mappings to HashMap
    primeNumbers.put("Two", 2);
    primeNumbers.put("Three", 3);
    System.out.println("Prime Numbers: " + primeNumbers);

    // create another HashMap
    HashMap<String, Integer> numbers = new HashMap<>();
    numbers.put("One", 1);
    numbers.put("Two", 22);

    // Add all mappings from primeNumbers to numbers
    numbers.putAll(primeNumbers);
    System.out.println("Numbers: " + numbers);
  }
}

Output

Prime Numbers: {Two=2, Three=3}
Numbers: {One=1, Two=2, Three=3}

In the above example, we have created two hashmaps named primeNumbers and numbers. Notice the line,

numbers.putAll(primeNumbers);

Here, the putAll() method adds all the mappings from primeNumbers to numbers.

Notice that the value for the key Two is changed from 22 to 2. It is because key Two is already present in numbers. Hence, the value is replaced by the new value from primeNumbers.

Note: We have used the put() method to add a single mapping to the hashmap. To learn more, visit Java HashMap put().


Example 2: Insert Mappings from TreeMap to HashMap

import java.util.HashMap;
import java.util.TreeMap;

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

    // create a TreeMap of String type
    TreeMap<String, String> treemap = new TreeMap<>();

    // add mappings to the TreeMap
    treemap.put("A", "Apple");
    treemap.put("B", "Ball");
    treemap.put("C", "Cat");
    System.out.println("TreeMap: " + treemap);

    // create a HashMap
    HashMap<String, String> hashmap = new HashMap<>();

    // add mapping to HashMap
    hashmap.put("Y", "Yak");
    hashmap.put("Z", "Zebra");
    System.out.println("Initial HashMap: " + hashmap);

    // add all mappings from TreeMap to HashMap
    hashmap.putAll(treemap);
    System.out.println("Updated HashMap: " + hashmap);
  }
}

Output

TreeMap: {A=Apple, B=Ball, C=Cat}
Initial HashMap: {Y=Yak, Z=Zebra}
Updated HashMap: {A=Apple, B=Ball, C=Cat, Y=Yak, Z=Zebra}

In the above example, we have created a TreeMap and a HashMap. Notice the line,

hashmap.putAll(treemap);

Here, we have used the putAll() method to add all the mappings from treemap to hashmap.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges