Udemy logo

java treemapThe Map interface is a part of Java Collections Framework in which keys are mapped to values. Keys are unique in a single implementation and each key is mapped to only one value, but one value can mapped to a multiple keys. The Map interface provides three different collection views (set of keys, collection of values and a set of key-value mappings) to retrieve or examine its content. It replaced the obsolete abstract class ‘Dictionary’. Java has three types of map implementations, which are ‘HashMap’, ‘LinkedHashMap’ and ‘TreeMap’.  The Java ‘TreeMap’ is most frequently used since it guarantees the specified order in which the iterators on the collection view return the elements of a map.

What is a Java TreeMap?

The Java ‘TreeMap’ is an implementation of the Map interface based on a Red-Black tree, which is a data structure of type self balancing binary search tree. Unlike ‘HashMap’, ‘TreeMap’ is a ‘SortedMap’, which maintains the order of keys on object insertion. In Java, ‘TreeMap’ class resides in ‘java.util’ package. The ‘java.util.TreeMap’ class inherits methods from ‘java.util.AbstractMap’ and implements the ‘java.util.Map’, ‘java.util.SortedMap’ and ‘java.util.NavigableMap’ interfaces.

To explore more Java classes, take a course at Udemy.com.

Java TreeMap Constructors

The ‘java.util.TreeMap’ class provides different constructors to instantiate the ‘TreeMap’ object. Following are the structures of constructors.

TreeMap Map_With_Natural_Order_Keys = new TreeMap ()
TreeMap Map_With_Custom_Order_Keys = new TreeMap ([Comparator])
TreeMap Map_With_Natural_Order_Keys = new TreeMap ([Map])
TreeMap Map_With_SortedMap_Order = new TreeMap ([SortedMap])

In the above format, first constructor creates a new and empty tree map with the natural ordering of its keys and when a sort order is provide as a ‘Comparator’, the default sorting order will change with the provided one. A ‘Map’ as an argument in a constructor returns the ‘TreeMap’ object with same mapping as of ‘map’ but a natural ascending ordering is applied to them. Finally, passing ‘SortedMap’ as an argument results in a ‘TreeMap’ object with same mapping and sorting specified in a sorted map.

Java TreeMap Methods ‘put’ and ‘putAll’

null or previous_Value = treeMap.put (key, value)
treeMap.putAll (Map)

Java ‘TreeMap’ method ‘put’ is used to insert a new key value pair or replace the object associated with specified key, when a key exists in a map. From the format, it is clear that it returns a null when a key is not already mapped or previous value, mapped with specified key. Following code snippet illustrates the mentioned description.

Code snippet:

import java.util.*;
TreeMap <String, String> alphaNumeric = new TreeMap <String, String> ();
alphaNumeric.put ("2", "Two");
alphaNumeric.put ("1", "One");
alphaNumeric.put ("3", "Four");
alphaNumeric.put ("5", "Five");
alphaNumeric.put ("4", "Four");
System.out.println ("" + alphaNumeric);
System.out.println ("Value returned: " + alphaNumeric.put ("6", "Six"));
System.out.println ("Value returned: " + alphaNumeric.put ("3", "Three"));
System.out.println ("" + alphaNumeric); // {1=One, 2=Two, 3=Three,
4=Four, 5=Five, 6=Six}

The ‘putAll’ method is an advanced variant of Java TreeMap ‘put’ method, in which all the mapping specified in ‘map’ argument is inserted with the ascending or specified order of keys, and replace the mapping already in a ‘TreeMap’ object with the new values of same keys in ‘map’ argument. It throws exceptions of ‘ClassCastException’ and ‘NullPointerException’ when a failure occurs in insertion or updating the key or value, and the specified map as an argument is null or have a null key respectively. Following change in code snippet shows the behavior of ‘putAll’ method.

Code snippet:

TreeMap <String, String> alphaNumeric = new TreeMap <String, String> ();
TreeMap <String, String> alphaNumericTemp = new TreeMap <String, String> ();
alphaNumeric.put ("2", "Two");
alphaNumeric.put ("1", "One");
alphaNumeric.put ("3", "Four");
alphaNumeric.put ("5", "Five");
alphaNumeric.put ("4", "Four");
alphaNumericTemp.put ("6", "Six");
alphaNumericTemp.put ("3", "Three");
alphaNumeric.putAll (alphaNumericTemp);
System.out.println ("" + alphaNumeric);

To learn essentials of Java, look at a tutorial at Udemy.com.

Java TreeMap Method ‘get’

null or value = treeMap.get (key)

The ‘get’ method of ‘TreeMap’ object retrieves the value of a provided key as an argument. From the format it is clear that it returns value of key or null when no mapped value exists in map for that key. It throws exceptions of ‘ClassCastException’ and ‘NullPointerException’, when a specified key cannot be compared with the keys in map and a provided key is null respectively.

Code snippet:

TreeMap <Integer, String> sportRanks = new TreeMap <Integer, String> ();
sportRanks.put (2, "Cricket");
sportRanks.put (1, "Soccer");
sportRanks.put (3, "BasketBall");
System.out.println ("Most Popular Sport: " + sportRanks.get (1));

Use of Iterator on Java TreeMap

Iterator in Java traverses through the entire Java Collection, thus it can also be used to iterate over the objects of the type Java ‘TreeMap’ . The iterator uses the ‘hasNext’ method to find out whether the next element exists or not, when it exists, a ‘next’ method is called to iterate that element. Following code snippet demonstrate the use of Iterator.

Code snippet:

TreeMap <String, String> fruitNames = new TreeMap <String, String> ();
fruitNames.put ("O", "Orange");
fruitNames.put ("A", "Apple");
fruitNames.put ("M", "Mango");
Set set = fruitNames.entrySet ();
Iterator treeIterator = set.iterator ();
while (treeIterator.hasNext ()) {
Map.Entry me = (Map.Entry) treeIterator.next ();
System.out.print (me.getKey () + ": ");
System.out.println (me.getValue ());

Java TreeMap Methods ‘clear’, ‘remove’, ‘containsKey’ and ‘containsValue’

treeMap.clear ()
null or value = treeMap.remove (key)
Boolean treeMap.containsKey (key)
Boolean treeMap.containsValue (value)

In above formats of Java TreeMap methods ‘clear’ removes all the mapping in the caller object whereas ‘remove’ method deletes only a single mapping with a provided key. A ‘remove’ method returns the value of a key that is deleted or null if the specified key does not exist. The ‘containsKey’ and ‘containsValue’ methods check the existence of key and value in a map respectively and return a true on a search hit or otherwise, false. Following is the example.

Code snippet:

TreeMap <String, String> fruitNames = new TreeMap <String, String> ();
fruitNames.put ("O", "Orange");
fruitNames.put ("A", "Apple");
fruitNames.put ("M", "Mango");
fruitNames.put ("B", "Apple");
System.out.println ("Have Key A: " + fruitNames.containsKey ("A"));
System.out.println ("Have Value Banana: " + fruitNames.containsValue ("Banana"));
fruitNames.remove ("A");
System.out.println (fruitNames); // {B=Apple, M=Mango, O=Orange}
fruitNames.clear ();
System.out.println (fruitNames); // {}

Java TreeMap method ‘descendingMap’

NavigableMap treeMap.descendingMap ()

The ‘descendingMap’ method of Java ‘TreeMap’ reverses the current order of mappings in a map. To illustrate this behavior following code is used.

 Code snippet:

NavigableMap <String, String> fruitNames = new TreeMap <String, String> ();
fruitNames.put ("O", "Orange");
fruitNames.put ("A", "Apple");
fruitNames.put ("M", "Mango");
System.out.println (fruitNames); // {A=Apple, M=Mango, O=Orange}
fruitNames = fruitNames.descendingMap ();
System.out.println (fruitNames); // {O=Orange, M=Mango, A=Apple}

Interested in learning more about Java? Take a course at Udemy.com.

Page Last Updated: May 2014

Top courses in Java

Java for Beginners
Navin Reddy
4.5 (1,524)
Learn Selenium with Java, Cucumber & Frameworks
Pavan Kumar
4.6 (7,764)
Java SE 11 Developer 1Z0-819 OCP Course - Part 1
Tim Buchalka, Tim Buchalka's Learn Programming Academy
4.7 (4,033)
Oracle Java Certification - Pass the Associate 1Z0-808 Exam.
Tim Buchalka's Learn Programming Academy, Goran Lochert
4.5 (5,832)
Modern Java - Learn Java 8 Features By coding it
Pragmatic Code School
4.5 (11,129)

More Java Courses

Java students also learn

Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.

Request a demo