bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Java/Java Data Structures
Java•Java Data Structures

Java TreeMap

Native lesson simulator

Hash map lookup

Hash the key, jump to a bucket, then compare entries there.

Ada -> bucket 20Cy:21Bo:22Ada:3Dee:33

Ada hashes to bucket 2; lookup only scans entries in that bucket.

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind Java TreeMap?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

import java.util.TreeMap; // Import the TreeMap ___
3Order

Put the learning moves in the order that makes the concept easiest to apply.

A TreeMap is a collection that stores key/value pairs in sorted order by key .
TreeMap vs HashMap
Loop Through a 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);
  }
}

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:

capitalCities.get("England");

Remove Items

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

capitalCities.remove("England");

Use clear() to remove all items

capitalCities.clear();

TreeMap Size

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

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

FeatureHashMapTreeMap
OrderNo guaranteed orderSorted by keys
Null KeysAllows one null keyDoes not allow null keys
PerformanceFaster (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:

// 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.

Previous

Java HashMap

Next

Java LinkedHashMap