CodesJava

Easy learning with example program codes

Copy map content to another hashmap in java

We can use putAll() method to copy map content to another hashmap in java.

putAll(Map m): Puts all the entries from m into this map.

Syntax:

public void putAll(Map m)

Example

package com.codesjava;
 
import java.util.HashMap;
 
public class Test {
  public static void main(String args[]){
	//Create HashMap object.
	HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
 
	//Add objects to the HashSet.
	hashMap.put(4, "Roxy");
	hashMap.put(2, "Sunil");
	hashMap.put(5, "Sandy");
	hashMap.put(1, "Munish");
	hashMap.put(3, "Pardeep");
 	//Print the HashMap object.
	System.out.println("HashMap elements:");
	System.out.println(hashMap);
 
	//Create a sub map
	HashMap<Integer, String> subMap = new HashMap<Integer, String>();
	//Add elements
        subMap.put(6, "Ajay");
        subMap.put(7, "Vikas");
        hashMap.putAll(subMap);
 
        //Print the HashMap object.
      	System.out.println("HashMap elements:");
      	System.out.println(hashMap);
  }
}

Output

HashMap elements:
{1=Munish, 2=Sunil, 3=Pardeep, 4=Roxy, 5=Sandy}
HashMap elements:
{1=Munish, 2=Sunil, 3=Pardeep, 4=Roxy, 5=Sandy, 6=Ajay, 7=Vikas}
Please follow and like us:
error








Copyright © 2019 CodesJava DMCA.com Protection Status