Menu
Topics Index
...
`


Collections Framework > Map Classes >
Siva Nookala - 03 Mar 2017
TreeMap is a Red-Black Tree based Map implementation. The TreeMap is sorted based on the natural ordering of its keys or by a Comparator provided in the constructor.

TreeMap supports four constructors :
Constructor Description
TreeMap() Constructs a new, empty TreeMap, using the natural ordering of its keys.
TreeMap(Comparator comparator) Constructs a new, empty TreeMap, ordered according to the given comparator.
TreeMap(Map m) Constructs a new TreeMap containing the same mappings as the given Map, ordered according to the natural ordering of its keys.
TreeMap(SortedMap m) Constructs a new TreeMap containing the same mappings and using the same ordering as the specified SortedMap.
  • The key-value value pairs in a TreeMap are sorted.
  • TreeMap stores only unique key values. When it encounters a key value that is already present in the map it updates the new entry (on the previous entry with new value for the specified key).
  • Duplicate values can be present in a TreeMap.
Here is a sample implementation of TreeMap :
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);    
    }
}
OUTPUT

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}

DESCRIPTION

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.

THINGS TO TRY
  • 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".
The below is a program which shows the use of Comparator in TreeMap
TreeMapUsingComparator
import java.util.*;

class TreeMapUsingComparator
{
    TreeMap descendingorder = new TreeMap<>(new Comparator<Integer>()//LINE A
    {
    
        public int compare(Integer first, Integer second)
        {
            return second.compareTo(first);//LINE B
        }
    });
    descendingorder.put(1, "first");
    descendingorder.put(0, "zero");
    descendingorder.put(3, "third");
    descendingorder.put(5, "five");
    descendingorder.put(4, "four"); // LINE C
    System.out.println("Map sorted according to the comparator : " + descendingorder);
}
OUTPUT

Map sorted according to the comparator : {5=five, 4=four, 3=third, 1=first, 0=zero}

DESCRIPTION

In the above program at LINE A we used a Comparator that sorts the TreeMap in descending order.

THINGS TO TRY
  • In the above program interchange first and second so that the map is printed in ascending order.
  • Include the following code after LINE C.
    descendingorder.put(4, "four");
    The entry will get included in the output.
The following program explains the methods in TreeMap.
TreeMapUsingmethods
import java.util.*;

class TreeMapUsingmethods
{
    TreeMap statecapitals = new TreeMap<>();
    statecapitals.put("Andhra Pradesh", "Hyderabad");
    statecapitals.put("Arunachal Pradesh", "Itanagar");
    statecapitals.put("Bihar", "Patna");
    statecapitals.put("Goa", "Panaji");
    statecapitals.put("Kerala", "Thiruvananthapuram");
    System.out.println(statecapitals); // LINE A
    //Returns true if map contains the key otherwise false
    System.out.println("Map contains key Karnataka : " + statecapitals.containsKey("Karntatka")); // LINE B
    //Returns true if map contains the value otherwise false
    System.out.println("Map contains value Panaji : " + statecapitals.containsValue("Panaji")); // LINE C
    statecapitals.remove("Kerala"); // LINE D
    System.out.println("Map after removing Kerala : "); // LINE E
    System.out.println(statecapitals);// LINE F
}
OUTPUT

{Andhra Pradesh=Hyderabad, Arunachal Pradesh=Itanagar, Bihar=Patna, Goa=Panaji, Kerala=Thiruvananthapuram}
Map contains key Karnataka : false
Map contains value Panaji : true
Map after removing Kerala :
{Andhra Pradesh=Hyderabad, Arunachal Pradesh=Itanagar, Bihar=Patna, Goa=Panaji}

DESCRIPTION

At LINE A the entries in the TreeMap are printed.
At LINE B containsKey is used to know whether map contains key Karnataka
, the return type of the containsKey containValue and method is boolean.
At LINE C containsValue is used to know whether map contains value Panaji. At LINE D the entry Kerala is removed from the map by using remove method.
AT LINE F the map after removing Kerala is printed.

THINGS TO TRY
  • Use entrySet to return a setview of the map as shown below.
    Set<Entry<Integer, String>> setview = statecapitals.entrySet();
    System.out.println("Set view of the entries : " + setview);
    Place the code after LINE F and see the output. Set view of the map is returned.

Dependent Topics : Java Map Interfaces - HashMap, TreeMap, LinkedHashMap 

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.