← Back to Chapters

Java TreeMap

? Java TreeMap

? Quick Overview

TreeMap is a part of the Java Collections Framework that stores elements in key-value pairs and keeps the keys automatically sorted.

? Key Concepts

  • Implements the Map interface
  • Stores data in sorted order by keys
  • Based on Red-Black Tree
  • Does not allow duplicate keys
  • Allows multiple null values but no null keys

? Syntax / Theory

TreeMap sorts keys using their natural ordering or by a custom Comparator provided at creation time.

? View Code Example
// Demonstration of TreeMap in Java
import java.util.TreeMap;

public class TreeMapDemo {
public static void main(String[] args) {

// Creating a TreeMap
TreeMap map=new TreeMap<>();

// Adding elements to TreeMap
map.put(3,"Java");
map.put(1,"HTML");
map.put(2,"CSS");

// Displaying sorted TreeMap
System.out.println(map);
}
}

? Live Output / Explanation

The output is sorted automatically by key:
{1=HTML, 2=CSS, 3=Java}

? Interactive Simulator

Add items (Key must be Number) to see them automatically sort!

 

? Tips & Best Practices

  • Use TreeMap when sorted key order is required
  • Avoid using null keys to prevent exceptions
  • Use Comparator for custom sorting logic

? Try It Yourself

  • Add more elements and observe automatic sorting
  • Use descendingMap() for reverse order
  • Create a TreeMap with a custom Comparator