What is TreeMap in Java?

A TreeMap in Java is part of the Java Collections Framework and implements the Map interface. It is a red-black tree-based implementation that stores the keys in a sorted order. This enables fast retrieval, insertion, and deletion of key-value pairs based on their natural ordering or a specified comparator.

Some important features of a TreeMap include:

  • Sorted Order: It maintains the order of keys based on their natural ordering or a custom comparator.
  • Null Values: It does not allow null keys but allows null values.
  • Performance: The operations like get, put, and remove have O(log n) time complexity.

Here’s a simple example demonstrating the usage of TreeMap:

import java.util.TreeMap; public class TreeMapExample { public static void main(String[] args) { // Create a TreeMap TreeMap treeMap = new TreeMap<>(); // Adding key-value pairs to the TreeMap treeMap.put(3, "Three"); treeMap.put(1, "One"); treeMap.put(2, "Two"); // Displaying the TreeMap System.out.println("TreeMap: " + treeMap); // Retrieving a value String value = treeMap.get(2); System.out.println("Value for key 2: " + value); } }

TreeMap Java TreeMap Java Collections Map interface sorted map