Java HashMap putAll() Method

Java HashMap Java HashMap

The putAll() method inserts all the specified key/value pairs into the HashMap.

The syntax of the putAll() method is:

hashmap.putAll(Map m)

Note:hashmap is an object of the HashMap class.

Parameter Details:

  • m - contains the mappings to be inserted into the HashMap

Return Value

It does not return any value.

Example

The following example demonstrates the use of the putAll() method:

Example

import java.util.HashMap;

class Main {
    public static void main(String[] args) {
        // Create a HashMap
        HashMap<Integer, String> sites = new HashMap<>();

        // Add some elements to the HashMap
        sites.put(1, "Google");
        sites.put(2, "Example");
        sites.put(3, "Taobao");
        System.out.println("sites HashMap: " + sites);
        // Create another HashMap
        HashMap<Integer, String> sites2 = new HashMap<>();
        sites2.put(1, "Weibo");  // Existing values will be replaced
        sites2.put(4, "Wiki");

        // Add all mappings from sites to sites2
        sites2.putAll(sites);
        System.out.println("sites2 HashMap: " + sites2);
    }
}

Executing the above program produces the following output:

sites HashMap: {1=Google, 2=Example, 3=Taobao}
sites2 HashMap: {1=Google, 2=Example, 3=Taobao, 4=Wiki}

In the above example, we created two HashMaps: sites and site2. Later in the code, the putAll() method is used to insert sites' key/value pairs into site2. Since key 1 already exists in site2, the corresponding value from sites will replace the corresponding value in site2.

Inserting a single key/valueJava HashMap put() Method。

Java HashMap Java HashMap

Other Extensions