Signup/Sign In

Java Collection Framework Treemap

The TreeMap class is a implementation of Map interface based on red-black tree. It provides an efficient way of storing key-value pairs in sorted order.

It is similar to HashMap class except it is sorted in the ascending order of its keys. It is not suitable for thread-safe operations due to its unsynchronized nature.

It implements NavigableMap interface and extends AbstractMap class. Declaration of this class is given below.

TreeMap Declaration

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

Important Points:

  • It contains only unique elements.
  • It cannot have a null key but can have multiple null values.
  • It is non synchronized.
  • It maintains ascending order.

TreeMap Constructors

Constructor Description
TreeMap() It creates a new, empty tree map, using the natural ordering of its keys.
TreeMap(Comparator<? super K> comparator) It created a new, empty tree map, ordered according to the given comparator.
TreeMap(Map<? extends K,? extends V> m) It creates a new tree map containing the same mappings as the given map.
TreeMap(SortedMap<K,? extends V> m) It creates a new tree map containing sortedamp.

Example : Creating TreeMap

Lets take an example to understand the creation of treeMap which is initially empty.

  
class Demo
{
  public static void main(String args[])
  {
    // Creating TreeMap
    TreeMap<String,Integer> treeMap = new TreeMap<String,Integer>();
    // Displaying TreeMap
    System.out.println(treeMap);
  }
}
  

{}

TreeMap Methods

This table contains the methods of TreeMap that can be used to manipulate objects.

Map.Entry<K,V> ceilingEntry(K key) It returns the key-value pair having the least key, greater than or equal to the specified key, or null if there is no such key.
K ceilingKey(K key) It returns the least key, greater than the specified key or null if there is no such key.
void clear() It removes all the key-value pairs from a map.
Object clone() It returns a shallow copy of TreeMap instance.
Comparator<? super K> comparator() It returns the comparator that arranges the key in order, or null if the map uses the natural ordering.
NavigableSet<K> descendingKeySet() It returns a reverse order NavigableSet view of the keys contained in the map.
NavigableMap<K,V> descendingMap() It returns the specified key-value pairs in descending order.
Map.Entry firstEntry() It returns the key-value pair having the least key.
Map.Entry<K,V> floorEntry(K key) It returns the greatest key, less than or equal to the specified key, or null if there is no such key.
void forEach(BiConsumer<? super K,? super V> action) It performs the given action for each entry in the map until all entries have been processed or the action throws an exception.
SortedMap<K,V> headMap(K toKey) It returns the key-value pairs whose keys are strictly less than toKey.
NavigableMap<K,V> headMap(K toKey, boolean inclusive) It returns the key-value pairs whose keys are less than (or equal to if inclusive is true) toKey.
Map.Entry<K,V> higherEntry(K key) It returns the least key strictly greater than the given key, or null if there is no such key.
K higherKey(K key) It is used to return true if this map contains a mapping for the specified key.
Set keySet() It returns the collection of keys exist in the map.
Map.Entry<K,V> lastEntry() It returns the key-value pair having the greatest key, or null if there is no such key.
Map.Entry<K,V> lowerEntry(K key) It returns a key-value mapping associated with the greatest key strictly less than the given key, or null if there is no such key.
K lowerKey(K key) It returns the greatest key strictly less than the given key, or null if there is no such key.
NavigableSet navigableKeySet() It returns a NavigableSet view of the keys contained in this map.
Map.Entry<K,V> pollFirstEntry() It removes and returns a key-value mapping associated with the least key in this map, or null if the map is empty.
Map.Entry<K,V> pollLastEntry() It removes and returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.
V put(K key, V value) It inserts the specified value with the specified key in the map.
void putAll(Map<? extends K,? extends V> map) It is used to copy all the key-value pair from one map to another map.
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V newValue) It replaces the old value with the new value for a specified key.
void replaceAll(BiFunction<? super K,? super V,? extends V> function) It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) It returns key-value pairs whose keys range from fromKey to toKey.
SortedMap<K,V> subMap(K fromKey, K toKey) It returns key-value pairs whose keys range from fromKey, inclusive, to toKey, exclusive.
SortedMap<K,V> tailMap(K fromKey) It returns key-value pairs whose keys are greater than or equal to fromKey.
NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) It returns key-value pairs whose keys are greater than (or equal to, if inclusive is true) fromKey.
boolean containsKey(Object key) It returns true if the map contains a mapping for the specified key.
boolean containsValue(Object value) It returns true if the map maps one or more keys to the specified value.
K firstKey() It is used to return the first (lowest) key currently in this sorted map.
V get(Object key) It is used to return the value to which the map maps the specified key.
K lastKey() It is used to return the last (highest) key currently in the sorted map.
V remove(Object key) It removes the key-value pair of the specified key from the map.
int size() It returns the number of key-value pairs exists in the hashtable.
Collection values() It returns a collection view of the values contained in the map.

Example : Adding Elements to TreeMap

After creating TreeMap, lets add elements to it. We used put method to insert elements which takes two arguments: first is key and second is value.

  
    class Demo
{
  public static void main(String args[])
  {
    // Creating TreeMap
    TreeMap<String,Integer> treeMap = new TreeMap<String,Integer>();
    // Adding elements
    treeMap.put("a",100);
    treeMap.put("b",200);
    treeMap.put("c",300);
    treeMap.put("d",400);
    // Displaying TreeMap
    System.out.println(treeMap);
  }      
  

{a=100, b=200, c=300, d=400}

Get first and last key in LinkedHashMap

We can get first and last element of the map using the firstEntry() and lastEntry() method. It returns a pair of key and value.

  
import java.util.*;

class Demo
{
  public static void main(String args[])
  {
    // Creating TreeMap
    TreeMap<String,Integer> treeMap = new TreeMap<String,Integer>();
    // Adding elements
    treeMap.put("a",100);
    treeMap.put("b",200);
    treeMap.put("c",300);
    treeMap.put("d",400);
    // Displaying TreeMap
    System.out.println(treeMap);
    // First Element
    System.out.println("First Element: "+treeMap.firstEntry());
    // Last Element
    System.out.println("Last Element: "+treeMap.lastEntry());
    
  }
}
  

{a=100, b=200, c=300, d=400} First Element: a=100 Last Element: d=400

Example: Find HeadMap and TailMap of the TreeMap

We can get head elements and tail elements of the TreeMap by using the headMap() and tailMap() methods. These methods return a map containing the elements.

  
import java.util.*;

class Demo
{
  public static void main(String args[])
  {
    // Creating TreeMap
    TreeMap<String,Integer> treeMap = new TreeMap<String,Integer>();
    // Adding elements
    treeMap.put("a",100);
    treeMap.put("b",200);
    treeMap.put("c",300);
    treeMap.put("d",400);
    // Displaying TreeMap
    System.out.println(treeMap);
    // Head Map
    System.out.println("Head Map: "+treeMap.headMap("c"));
    // Tail Map
    System.out.println("Tail Map: "+treeMap.tailMap("c"));
    
  }
}
  

{a=100, b=200, c=300, d=400} Head Map: {a=100, b=200} Tail Map: {c=300, d=400}

Example: Iterating TreeMap

In this example, we are creating TreeMap to store data. It uses tree to store data and data is always in sorted order and iterating the map using loop. See the below example.

  
  import java.util.*;

class Demo
{
  public static void main(String args[])
  {
    TreeMap<String,Integer> tm = new TreeMap<String,Integer>();
    tm.put("a",100);
    tm.put("b",200);
    tm.put("c",300);
    tm.put("d",400);

    Set<Map.Entry<String,Integer>> st = tm.entrySet();
    for(Map.Entry<String,Integer> me:st)
    {
      System.out.print(me.getKey()+":");
      System.out.println(me.getValue());
    }
  }
}
  

a:100 b:200 c:300 d:400