Java TreeMap
A TreeMap is a class in the Java Collections Framework that stores data as
key-value pairs while automatically keeping its keys in sorted (ascending)
order.
The TreeMap class belongs to the java.util package and implements the Map
interface. Unlike a HashMap, which stores entries in an unpredictable order,
a TreeMap organizes its keys using their natural ordering or a custom
Comparator.
A TreeMap is ideal when your application requires data to remain sorted,
such as maintaining
alphabetical lists, ranking systems, or ordered records.
Why Use TreeMap?
Use a TreeMap when you need to:
- Store data as key-value pairs.
- Automatically sort entries by key.
- Perform efficient searches based on sorted keys.
- Retrieve the smallest or largest key quickly.
- Maintain ordered data without manually sorting it.
Tip: If key ordering is important, use a TreeMap. If performance
is more important than ordering, consider using a HashMap.
Creating a TreeMap
To use a TreeMap, import the java.util.TreeMap class and create an
object by specifying the data types for its keys and values.
Example
The following program creates a TreeMap that stores course codes and
course names.
import java.util.TreeMap;
public class CourseMapExample {
public static void main(String[] args) {
TreeMap<String, String> courses = new
TreeMap<>();
courses.put("CS101", "Introduction to
Programming");
courses.put("CS301", "Database
Systems");
courses.put("CS201", "Data
Structures");
System.out.println(courses);
}
}
Output
{CS101=Introduction to Programming, CS201=Data Structures,
CS301=Database Systems}
Notice that the keys are displayed in ascending alphabetical
order.
Adding Items
Use the `put()` method to insert key-value pairs into a TreeMap. If the
specified key already exists, its value is updated.
Example
import java.util.TreeMap;
public class LibraryExample {
public static void main(String[] args) {
TreeMap<Integer, String> books = new
TreeMap<>();
books.put(104, "Java
Programming");
books.put(101, "Python
Essentials");
books.put(103, "Data Science");
books.put(102, "Web
Development");
// Update an existing key
books.put(103, "Advanced Data
Science");
System.out.println(books);
}
}
Output
{101=Python Essentials, 102=Web Development, 103=Advanced Data Science,
104=Java
Programming}
Note: A TreeMap does not allow duplicate keys. Adding the same
key again replaces the
existing value.
Accessing an Item
Use the get() method to retrieve the value associated with a specific
key.
Example
import java.util.TreeMap;
public class AccessExample {
public static void main(String[] args) {
TreeMap<String, Double> products =
new TreeMap<>();
products.put("Laptop",
74999.0);
products.put("Monitor",
18999.0);
System.out.println(products.get("Laptop"));
}
}
Output
74999.0
Removing Items
Use the remove() method to delete a key-value pair.
Example
import java.util.TreeMap;
public class RemoveExample {
public static void main(String[] args) {
TreeMap<String, Integer> scores = new
TreeMap<>();
scores.put("Alice", 92);
scores.put("Brian", 85);
scores.put("Chris", 90);
scores.remove("Brian");
System.out.println(scores);
}
}
To remove every entry from the map, use the clear() method.
scores.clear();
Finding the Size of a TreeMap
Use the size() method to determine the number of key-value pairs stored
in the map.
Example
import java.util.TreeMap;
public class SizeExample {
public static void main(String[] args) {
TreeMap<String, String> cities = new
TreeMap<>();
cities.put("FR", "Paris");
cities.put("JP", "Tokyo");
cities.put("IN", "New Delhi");
System.out.println("Total Entries: " +
cities.size());
}
}
Output
Total Entries: 3
Note:The size counts only unique keys. Updating an existing key
does not increase the size of the map.
Looping Through a TreeMap
A TreeMap can be traversed in several ways.
Print All Keys
for (String key : countries.keySet()) {
System.out.println(key);
}
Print All Values
for (String value : countries.values()) {
System.out.println(value);
}
Print Keys and Values
The entrySet() method is the most efficient way to iterate through a
`TreeMap`.
import java.util.Map;
import java.util.TreeMap;
public class EntrySetExample {
public static void main(String[] args) {
TreeMap<String, Integer> inventory =
new TreeMap<>();
inventory.put("Keyboard", 25);
inventory.put("Laptop", 8);
inventory.put("Mouse", 40);
for (Map.Entry<String, Integer> item
: inventory.entrySet()) {
System.out.println(item.getKey() + " : " + item.getValue());
}
}
}
Output
Keyboard : 25
Laptop : 8
Mouse : 40
Using the `var` Keyword (Java 10+)
Starting with Java 10, you can use `var` for local variable type
inference.
Without `var`
TreeMap<String, Integer> rankings = new
TreeMap<>();
With `var`
var rankings = new TreeMap<String, Integer>();
Using var reduces repetition, although many developers still prefer
explicit type declarations for better readability.
Declaring a TreeMap Using the Map Interface
A common Java best practice is to declare variables using the `Map`
interface instead of the implementation class.
Example
import java.util.Map;
import java.util.TreeMap;
public class MapInterfaceExample {
public static void main(String[] args) {
Map<Integer, String> departments =
new TreeMap<>();
departments.put(30, "Finance");
departments.put(10, "Human
Resources");
departments.put(20, "Sales");
System.out.println(departments);
}
}