TreeMap

TreeMap in Java is an implementation of the NavigableMap interface and extends AbstractMap. It stores key-value pairs in a sorted order based on the natural ordering of keys or a custom Comparator provided at the time of creation. TreeMap is implemented as a red-black tree, which provides guaranteed log(n) time complexity for most operations like put, get, and remove, making it efficient for scenarios where elements need to be sorted.

import java.util.TreeMap;

// Syntax for creating a TreeMap with natural ordering
TreeMap<KeyType, ValueType> mapName = new TreeMap<>();
Code language: JavaScript (javascript)

Commonly Used TreeMap Methods

 Basic Map Methods (from Map interface)

Method Description
V put(K key, V value) Adds a key-value pair to the map.
V get(Object key) Returns the value associated with the key.
V remove(Object key) Removes the key-value mapping.
boolean containsKey(Object key) Checks if key exists.
boolean containsValue(Object value) Checks if value exists.
int size() Returns the number of entries.
boolean isEmpty() Checks if map is empty.
void clear() Removes all mappings.
Set<K> keySet() Returns a set view of keys.
Collection<V> values() Returns a collection view of values.
Set<Map.Entry<K, V>> entrySet() Returns a set of key-value entries.

TreeMap-Specific Methods

Method Description
Comparator<? super K> comparator() Returns the comparator used or null if natural ordering.
K firstKey() Returns the first (lowest) key.
K lastKey() Returns the last (highest) key.
SortedMap<K,V> headMap(K toKey) Returns a view of the map whose keys are < toKey.
SortedMap<K,V> tailMap(K fromKey) Returns a view of the map whose keys are >= fromKey.
SortedMap<K,V> subMap(K fromKey, K toKey) Returns a view from fromKey (inclusive) to toKey (exclusive).

NavigableMap Methods (Advanced)

Method Description
K lowerKey(K key) Returns greatest key < key.
K floorKey(K key) Returns greatest key <= key.
K ceilingKey(K key) Returns least key >= key.
K higherKey(K key) Returns least key > key.
Map.Entry<K, V> pollFirstEntry() Removes and returns the first entry.
Map.Entry<K, V> pollLastEntry() Removes and returns the last entry.
NavigableMap<K, V> descendingMap() Returns a reverse-order view of the map.
NavigableSet<K> descendingKeySet() Returns keys in descending order.
NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) Flexible range view.
import java.util.TreeMap;
import java.util.Map;

public class TreeMapExample {
    public static void main(String[] args) {
        // Creating a TreeMap to store student names and their roll numbers
        TreeMap<String, Integer> studentMap = new TreeMap<>();

        // Adding students to the TreeMap
        studentMap.put("Paani", 101);
        studentMap.put("Mahesh", 102);
        studentMap.put("Datta", 103);
        studentMap.put("Ganesh", 104);
        studentMap.put("Harsha", 105);

        // Displaying the TreeMap
        System.out.println("TreeMap of students:");
        System.out.println(studentMap);

        // Removing a student from the TreeMap
        Integer removedRollNumber = studentMap.remove("Datta");
        System.out.println("\nRemoved student 'Datta' with roll number: " + removedRollNumber);

        // Displaying the updated TreeMap
        System.out.println("\nUpdated TreeMap of students:");
        System.out.println(studentMap);

        // Checking if a student exists in the TreeMap
        String searchStudent = "Harsha";
        boolean containsStudent = studentMap.containsKey(searchStudent);
        System.out.println("\nDoes the TreeMap contain student '" + searchStudent + "'? " + containsStudent);

        // Iterating over the entries of the TreeMap
        System.out.println("\nIterating over TreeMap entries:");
        for (Map.Entry<String, Integer> entry : studentMap.entrySet()) {
            System.out.println("Student: " + entry.getKey() + ", Roll Number: " + entry.getValue());
        }

        // Size of the TreeMap
        System.out.println("\nSize of the TreeMap: " + studentMap.size());

        // Clearing the TreeMap
        studentMap.clear();
        System.out.println("\nIs the TreeMap empty now? " + studentMap.isEmpty());
    }
}

D:\>javac TreeMapExample.java

D:\>java TreeMapExample
TreeMap of students:
{Datta=103, Ganesh=104, Harsha=105, Mahesh=102, Paani=101}

Removed student 'Datta' with roll number: 103

Updated TreeMap of students:
{Ganesh=104, Harsha=105, Mahesh=102, Paani=101}

Does the TreeMap contain student 'Harsha'? true

Iterating over TreeMap entries:
Student: Ganesh, Roll Number: 104
Student: Harsha, Roll Number: 105
Student: Mahesh, Roll Number: 102
Student: Paani, Roll Number: 101

Size of the TreeMap: 4

Is the TreeMap empty now? trueCode language: JavaScript (javascript)

TreeMap in Java is a powerful data structure for scenarios where elements need to be stored in a sorted order based on keys. It provides efficient operations for inserting, accessing, and removing elements, making it suitable for applications where sorted mappings are required. Understanding how to effectively use TreeMap allows developers to design efficient algorithms and manage data structures effectively in Java applications.

Scroll to Top