CodesJava

Easy learning with example program codes

how to copy map content to another treemap?


TreeMap

TreeMap extends AbstractMap class and implements the NavigableMap interface. It contains the elements in key-value pair form. It maintains ascending order for its elements. It not allowed duplicate key.

Note: A TreeMap can have only one null key but can have multiple null values.

We can use putAll() method to copy map content to another treemap.

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.TreeMap;
 
public class Test {
  public static void main(String args[]){
	//Create TreeMap object.
	TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>();
 
	//Add objects to the TreeMap.
	treeMap.put(4, "Roxy");
	treeMap.put(2, "Sunil");
	treeMap.put(5, "Sandy");
	treeMap.put(1, "Munish");
	treeMap.put(3, "Pardeep");
 
	//Print the TreeMap object.
	System.out.println("TreeMap elements:");
 
        System.out.println(treeMap);
 
	//Create sub map		
        TreeMap<Integer, String> subMap = new TreeMap<Integer, String>();
        subMap.put(6, "Sachin");
        subMap.put(7, "Sahil");
        //Copy submap elements into treemap
        treeMap.putAll(subMap); 
        //Print the TreeMap object.
      	System.out.println("TreeMap elements:");
      	System.out.println(treeMap);
  }
}

Output

TreeMap elements:
{1=Munish, 2=Sunil, 3=Pardeep, 4=Roxy, 5=Sandy}
TreeMap elements:
{1=Munish, 2=Sunil, 3=Pardeep, 4=Roxy, 5=Sandy, 6=Sachin, 7=Sahil}
Sign Up/ Sign In
Ask a Question


Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki