TreeMap put() and putAll() methods in Java

We will study about put() and putAll() methods in Java, in the present tutorial. Both put() and putAll() methods belongs to TreeMap class, which is an implementation class of NavigableMap Interface.

java.util.TreeMap.put() :

  • This method links the given value with the given key in the map. In case that key is already present, then updating it results in updation of key.
  • This method takes two method arguments or parameters, which are key and value.
  • Key is with which value is associated and value is to be associated with the given key.
  • It returns the previously associated with the key, or null if there was no mapping for key.
  • There are no Exceptions here.

 

java.util.TreeMap.putAll() :

 

  • This method copies all of the mappings from the specified map and overwrites in case of repeated key.
  • This method takes one parameter : map.
  • The parameter is for mapping to be stored.
  • This is not a return type method.
  • It can throw NullPointerException if specified map is null or the specified map contains null key.

 

Program :

Let’s see a program of TreeMap :

 

package java;

import java.util.*;

public class TM_Example
{
 public static void main(String[] args)
 {
  //Declaring a TreeMap of Integer and String
  TreeMap<Integer, String> tm1 = new TreeMap<Integer, String>();

  //Adding values in TreeMap
  tm1.put(100,"hundred");
  tm1.put(200,"two-hundred");
  tm1.put(300,"three-hundred");

  //Printing the TreeMap elements
  System.out.println("tm1 : "+tm1);

  //Declaring another TreeMap
  TreeMap<Integer, String> tm2 = new TreeMap<Integer, String>();

  //Adding first TreeMap elements in second TreeMap
  tm2.putAll(tm1);

  System.out.println("tm2 : "+tm2);
 
 }
}

 

Output :

After execution of the class TM_Example, the output of the program will be :

tm1 : {100=hundred, 200=two-hundred, 300=three-hundred}
tm2 : {100=hundred, 200=two-hundred, 300=three-hundred}

We can see in the output that we have inserted the same number of elements in the both tm1 and tm2, But making use of different methods. We have used put() for insertion of elements in tm1 and putAll() for tm2.

Leave a Reply