Topics Index

TreeMap Demo - Java Example Program

TreeMap Demo
import java.util.TreeMap;

class TreeMapTest
    public static void main(String arg[])
        TreeMap<Integer, String> studentmarks = new TreeMap<>(); // LINE A
        studentmarks.put(4, "Nyamath");
        studentmarks.put(2, "Pramod");
        studentmarks.put(5, "Amar");
        studentmarks.put(1, "Santosh");
        studentmarks.put(3, "Soumya"); // LINE B
        //Automatically sorts in ascending key order
        System.out.println("Map sorted in ascending key order : " + studentmarks); // LINE B
        // poll.FirstEntry returns the first entry in the  map and then it removes from map
        System.out.println("First entry in the map is : " + studentmarks.pollFirstEntry()); // LINE C
        System.out.println("Map after using pollFirstEntry : " + studentmarks);    

Map sorted in ascending key order : {1=Santosh, 2=Pramod, 3=Soumya, 4=Nyamath, 5=Amar}
First entry in the map is : 1=Santosh
Map after using pollFirstEntry : {2=Pramod, 3=Soumya, 4=Nyamath, 5=Amar}


At LINE A, an empty TreeMap with Integer,String as key-value pair.
At LINE B, the elements in studentmarks are printed. The elements in the studentmarks are ordered on their keys.
At LINE C, pollFirstEntry() method removes and returns the first key-value pair in the map.

  • Create a TreeMap with a Map and SortedMap (i.e.using other constructors).
  • Include the following code after LINE B :
    studentmarks.put(10, "Soumya");
    The entry will get included in the output, Since there is no key with the value 10.
  • Include the following code before LINE B :
    studentmarks.put(3, "Om");
    As key 3 is already present in the map, the previous value "soumya" is replaced by the current value "Om".

© meritcampus 2019

All Rights Reserved.

Open In App