Introduction

TreeMap is Red-Black tree based NavigableMap implementation. It implements Map interface similar to HashMap class. The main difference between them is that HashMap is an unordered collection while TreeMap is sorted in the ascending order of its keys. TreeMap is unsynchronized collection class which means it is not suitable for thread-safe operations until unless synchronized explicitly.

Example

import java.util.TreeMap; 
import java.util.Set; 
import java.util.Iterator; 
import java.util.Map; 

public class Details {  

  public static void main(String args[]) {   

    // Declare TreeMap   
    TreeMap<Integer, String> tmap = new TreeMap<Integer, String>();   

    // Adding elements   
    tmap.put(1, "Data1");   
    tmap.put(23, "Data2"); 
    tmap.put(2, "Data5");   

    // Display content using Iterator
    Set set = tmap.entrySet();   
    Iterator iterator = set.iterator();   
  
    while(iterator.hasNext()) {
      Map.Entry mentry = (Map.Entry)iterator.next();
      System.out.println("key is: "+ mentry.getKey() + " & Value is: " + mentry.getValue());   
    }
  }
}

Important methods

  • boolean containsKey(Object key)
    Returns true if this map contains a mapping for the specified key.
  • boolean containsValue(Object value)
    Returns true if this map maps one or more keys to the specified value.
  • Set<Map.Entry<K,V>> entrySet()
    Returns a Set view of the mappings contained in this map.
  • V get(Object key)
    Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
  • Set<K> keySet()
    Returns a Set view of the keys contained in this map.
  • V put(K key, V value)
    Associates the specified value with the specified key in this map.
  • V remove(Object key)
    Removes the mapping for this key from this TreeMap if present.
  • int size()
    Returns the number of key-value mappings in this map.
  • boolean isEmpty()
    Returns true if this map contains no key-value mappings.
  • boolean equals(Object o)
    Compares the specified object with this map for equality.
  • V replace(K key, V value)
    Replaces the entry for the specified key only if it is currently mapped to some value.

Important points

  • A TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.
  • It contains only unique elements.
  • It cannot have null key but can have multiple null values.
  • It is same as HashMap instead maintains ascending order.