Thursday 9 August 2012

Copy all the key-value pairs from one Map into another in Java


This Java Example shows how to copy all the key-value pairs from one Map into another using putAll(Map map) method of Java TreeMap class.

public void putAll(Map map)


Copies all of the mappings from the specified map to this map. These mappings replace any mappings that this map had for any of the keys currently in the specified map.

See the example given below:

import java.util.TreeMap;

public class CopyTreeMapExample {

 public static void main(String[] args) {

  // create TreeMap object
  TreeMap treeMap = new TreeMap();

  // add key value pairs to TreeMap
  treeMap.put("1", "One");
  treeMap.put("3", "Three");
  treeMap.put("2", "Two");
  treeMap.put("5", "Five");
  treeMap.put("4", "Four");

  // create TreeMap object to copy

  TreeMap copyTreeMap = new TreeMap();

  /**
   * putAll - Copies all of the mappings from
   * the specified map to this map.
   **/

  copyTreeMap.putAll(treeMap);

  System.out.println("copyTreeMap Map Contains:"+copyTreeMap);

 }
}


The output is:


copyTreeMap Map Contains : {1=One, 2=Two, 3=Three, 4=Four, 5=Five}

No comments:

Post a Comment