Java TreeMap Class

Introduction

The JavaTreeMap class is a “red-black” tree-based implementation. The TreeMap implements the NavigableMap interface which extends the Sorted Map and the Map interface in turn. TreeMap allows users to store key-value data pairs in a sorted technique.

Features of a TreeMap

  • Values in a TreeMap are dictated by the key. As mentioned above, this class implements the NavigableMap interface and extends the AbstractMap class.
  • Only unique elements are contained in a TreeMap. Duplicate copies are removed.
  • A TreeMap cannot have a null key. However, the values of the elements can be null.
  • TreeMap is non-synchronized
  • The Tree is sorted in the ascending order of keys.

Declaration Syntax

public class TreeMap <K,V> extends AbstractMap <K,V> implements NavigableMap <K,V>, Cloneable, Serializable

The two parameters used here are K and V. While K deals with the types of keys used and maintained in the map, V denotes the values associated with those key values. A key and value always occur in a pair as the key provides identity to the value.

Constructor

  • TreeMap() – Will construct an empty tree map that will be sorted according to the natural key order.
  • TreeMap (Comparator <? super K> comparator) – Here the comparator will determine how the empty TreeMap will be sorted after construction.
  • TreeMap (Map<? extends K,? extends V>m )- A new TreeMap will be created using the values of m. The map will then be sorted according to the natural key order.
  • TreeMap (SortedMap <K,? extends V> m) – Will construct a new tree map using the values of the sorted map m and according to the same order of the sorted map.

Example

import java.util.*;

class DemoTreeMap
{
public static void main (String args [])
{
TreeMap <Integer,String> map = new TreeMap <Integer, String>();

map.put(1,“Aaron”);
map.put(2,”Varun”);
map.put(3,”Akshay”);
map.put(4,”Rahul”);

for(Map.Entry m:map.entrySet())
{
System.out.println(m.getKey()+””+m.getValue());
}
}
}

 

OUTPUT

1 Aaron
2 Varun
3 Akshay
4 Rahul

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.