🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to Java Notes
Topic #110

Java TreeMap


Java TreeMap

A TreeMap is a collection that stores key/value pairs in sorted order by key.

It is part of the java.util package and implements the Map interface.

Tip: Unlike HashMap, which does not maintain order, TreeMap keeps its keys sorted.


Create a TreeMap

Create a TreeMap that stores String keys and String values:

Example

import java.util.TreeMap; // Import the TreeMap class

TreeMap<String, String> capitalCities = new TreeMap<>();

Now you can use methods like put(), get(), and remove() to manage sorted key/value pairs.


Add Items

Use the put() method to add key/value pairs:

Example

import java.util.TreeMap;

public class Main {
  public static void main(String[] args) {
    TreeMap<String, String> capitalCities = new TreeMap<>();
    capitalCities.put("England", "London");
    capitalCities.put("India", "New Dehli");
    capitalCities.put("Austria", "Wien");
    capitalCities.put("Norway", "Oslo");
    capitalCities.put("Norway", "Oslo"); // Duplicate
    capitalCities.put("USA", "Washington DC");

    System.out.println(capitalCities);
  }
}

Note: Output: The keys are sorted alphabetically (e.g., {Austria=Wien, England=London, India=New Dehli, Norway=Oslo, USA=Washington DC}). Note: Duplicates like "Norway" will only appear once.


Access an Item

Use get() with the key to access its value:

Example

capitalCities.get("England");

Remove Items

Use remove() to delete a key/value pair by key:

Example

capitalCities.remove("England");

Use clear() to remove all items:

Example

capitalCities.clear();

TreeMap Size

Use size() to count the number of key/value pairs:

Example

capitalCities.size();

Note: The size only counts unique keys. If a key is added more than once, only the latest value is kept.


Loop Through a TreeMap

Loop through the items of a TreeMap with a for-each loop.

Note: Use the keySet() method if you only want the keys, and use the values() method if you only want the values:

Example

// Print keys
for (String i : capitalCities.keySet()) {
  System.out.println(i);
}

Example

// Print values
for (String i : capitalCities.values()) {
  System.out.println(i);
}

Example

// Print keys and values
for (String i : capitalCities.keySet()) {
  System.out.println("key: " + i + " value: " + capitalCities.get(i));
}

TreeMap vs HashMap

Feature HashMap TreeMap
Order No guaranteed order Sorted by keys
Null Keys Allows one null key Does not allow null keys
Performance Faster (no sorting) Slower (maintains sorted order)

Tip: Use HashMap for performance, and TreeMap when you need sorted keys.


The var Keyword

From Java 10, you can use the var keyword to declare a TreeMap variable without writing the type twice. The compiler figures out the type from the value you assign.

This makes code shorter, but many developers still use the full type for clarity. Since var is valid Java, you may see it in other code, so it's good to know that it exists:

Example

// Without var
TreeMap<String, String> capitalCities = new TreeMap<String, String>();

// With var
var capitalCities = new TreeMap<String, String>();

The Map Interface

Note: Sometimes you will see both Map and TreeMap in Java code, like this:

import java.util.Map;
import java.util.TreeMap;

Map<String, String> capitalCities = new TreeMap<>();

This means the variable (capitalCities) is declared as a Map (the interface), but it stores a TreeMap object (the actual map). Since TreeMap implements the Map interface, this is possible.

It works the same way, but some developers prefer this style because it gives them more flexibility to change the type later.

Want to go beyond the notes?

Join CodingNow 2.0's Java course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Java TreeMap – FAQs

Quick answers about learning Java TreeMap in Java.

This free note from CodingNow 2.0 explains Java TreeMap in Java — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Java topic on CodingNow 2.0, including Java TreeMap, is 100% free with no signup required.
With focused practice, most students grasp Java TreeMap in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now