Loading

A TreeMap inJava is an implementation of the SortedMap interface that maintains key-value pairs in sorted order basedonthe keys. It is part of the Java Collections Framework and provides efficient operations for storing and retrieving data.

Features
  • Sorted Order: The elements in a TreeMap are sorted in natural order (ascending) of keys.
  • Implementation of NavigableMap: It provides navigation methods like higherKey(), lowerKey(), ceilingKey(), and floorKey().
  • No Duplicate Keys: It does not allow duplicate keys.
  • Performance: It provides O(log n) time complexity for operations like put(), get(), and remove().
  • Null Key Restriction: TreeMap does not allow null keys but permits multiple null values.


Example: Storing and Sorting Student Data in a TreeMap

package com.quipoin;

public class Student implements Comparable<Student>{
	int id;
	String name;
	public Student(int id, String name) {
		this.id=id;
		this.name=name;
	}
	@Override
	public String toString() {
		return id+"\t"+name;
	}
	@Override
	public int compareTo(Student std) {
		return this.id-std.id;
	}
}
package com.quipoin;

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

public class TestStudent {
	public static void main(String[] args) {
		Student s1=new Student(1011, "Prabhas");
		Student s2=new Student(1018, "Salman");
		Student s3=new Student(1013, "Aryan");
		Student s4=new Student(1016, "Pooja");

		TreeMap<Student, String> tm=new TreeMap<>();
		
	//Storing student object as key and their favorite language as the value
	
		tm.put(s1, "Java");
		tm.put(s2, "SQL");
		tm.put(s3, "Python");
		tm.put(s4, "C++");

		System.out.println("Student details!!");
		System.out.println("----------------------------");
		System.out.println("Id\tName\tFav_Language");
		System.out.println("----------------------------");
		Set<Student> student=tm.keySet();
		Iterator<Student> it=student.iterator();
		while(it.hasNext()) {
			Student key=it.next();
			String value=tm.get(key);
			System.out.println(key+"\t"+value);
		}
	}
}


Output:

Student details!!
----------------------------
Id	    Name	Fav_Language
----------------------------
1011	Prabhas	Java
1013	Aryan	Python
1016	Pooja	C++
1018	Salman	SQL

Key Point

  • Sorting Mechanism: Since Student implements Comparable, the TreeMap automatically arranges students in ascending order of their id. 
  • Iterating Over Entries: We use keySet() to retrieve all keys and display their values. 
  • Using Comparable: The compareTo() method ensures objects are sorted based on id. Without it, TreeMap throw a ClassCastException.

Two Minute Drill

  • TreeMap is a useful data structure when you need sorted key-value storage.
  • It does not allow null keys and maintains elements in a natural sorted order.
  • Implementing Comparable or providing a Comparator helps define custom sorting behavior.