Easy Tutorial
❮ Method Fibonacci Java String Tochararray ❯

Java HashMap putAll() Method

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

The syntax for the putAll() method is:

hashmap.putAll(Map m)

Note: hashmap is an object of the HashMap class.

Parameter Description:

Return Value

It does not return any value.

Example

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

import java.util.HashMap;

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

        // Add some elements to the HashMap
        sites.put(1, "Google");
        sites.put(2, "tutorialpro");
        sites.put(3, "Taobao");
        System.out.println("sites HashMap: " + sites);

        // Create another HashMap
        HashMap&lt;Integer, String> sites2 = new HashMap<>();
        sites2.put(1, "Weibo");  // Existing key 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 outputs:

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

In the above example, we created two HashMaps: sites and sites2. The code then uses the putAll() method to insert the key/value pairs from sites into sites2, where the key 1 in sites2 already exists, so the corresponding value in sites replaces the value in sites2.

To insert a single key/value pair, use the Java HashMap put() method.

❮ Method Fibonacci Java String Tochararray ❯