Java TreeMap Example

In this tutorial, we will explore the TreeMap class in Java, which is a specialized implementation of the Map interface. Unlike the standard HashMap, TreeMap maintains its entries in ascending order of the keys. This tutorial will demonstrate how to use TreeMap with examples, using the latest Java version to ensure modern practices and features.

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Step-by-Step Guide
    1. Creating a TreeMap
    2. Adding and Retrieving Elements
    3. Iterating Over the Map
    4. Using Custom Comparators
  4. Complete Code Example
  5. Conclusion

Introduction

TreeMap is a part of Java's java.util package and implements the NavigableMap interface. It maintains its entries in a sorted order based on the natural ordering of its keys or by a custom comparator provided at map creation time. TreeMap is typically used when there is a need to maintain a sorted order of keys.

Prerequisites

Before we start, ensure you have the following:

  • Java Development Kit (JDK) installed (latest version preferred)
  • An Integrated Development Environment (IDE) such as IntelliJ IDEA or Eclipse

Step-by-Step Guide

Step 1: Creating a TreeMap

First, let's create a TreeMap and add some key-value pairs to it.

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

public class TreeMapExample {
    public static void main(String[] args) {
        // Create a TreeMap
        Map<String, Integer> treeMap = new TreeMap<>();

        // Add key-value pairs to the map
        treeMap.put("Ravi", 25);
        treeMap.put("Sita", 30);
        treeMap.put("Arjun", 22);
        treeMap.put("Lakshmi", 20);

        // Print the map
        System.out.println("TreeMap: " + treeMap);
    }
}

Output:

TreeMap: {Arjun=22, Lakshmi=20, Ravi=25, Sita=30}

Step 2: Adding and Retrieving Elements

Let's add some elements to the TreeMap and retrieve values using different keys.

public class TreeMapExample {
    public static void main(String[] args) {
        // Create a TreeMap
        Map<String, Integer> treeMap = new TreeMap<>();

        // Add key-value pairs to the map
        treeMap.put("Ravi", 25);
        treeMap.put("Sita", 30);
        treeMap.put("Arjun", 22);
        treeMap.put("Lakshmi", 20);

        // Retrieve and print values using different keys
        System.out.println("Ravi: " + treeMap.get("Ravi"));
        System.out.println("Sita: " + treeMap.get("Sita"));
    }
}

Output:

Ravi: 25
Sita: 30

Step 3: Iterating Over the Map

We can iterate over the TreeMap using the entry set, key set, or values.

public class TreeMapExample {
    public static void main(String[] args) {
        // Create a TreeMap
        Map<String, Integer> treeMap = new TreeMap<>();

        // Add key-value pairs to the map
        treeMap.put("Ravi", 25);
        treeMap.put("Sita", 30);
        treeMap.put("Arjun", 22);
        treeMap.put("Lakshmi", 20);

        // Iterate over the map using entry set
        System.out.println("Iterating over TreeMap:");
        for (Map.Entry<String, Integer> entry : treeMap.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

Output:

Iterating over TreeMap:
Arjun: 22
Lakshmi: 20
Ravi: 25
Sita: 30

Step 4: Using Custom Comparators

We can use custom comparators to change the natural ordering of keys in the TreeMap. Let's create a TreeMap that sorts keys in descending order.

import java.util.Comparator;

public class TreeMapExample {
    public static void main(String[] args) {
        // Create a TreeMap with a custom comparator (descending order)
        Map<String, Integer> treeMap = new TreeMap<>(Comparator.reverseOrder());

        // Add key-value pairs to the map
        treeMap.put("Ravi", 25);
        treeMap.put("Sita", 30);
        treeMap.put("Arjun", 22);
        treeMap.put("Lakshmi", 20);

        // Print the map
        System.out.println("TreeMap (Descending Order): " + treeMap);
    }
}

Output:

TreeMap (Descending Order): {Sita=30, Ravi=25, Lakshmi=20, Arjun=22}

Complete Code Example

Here's the complete code example demonstrating various operations with TreeMap:

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

public class TreeMapExample {
    public static void main(String[] args) {
        // Create a TreeMap
        Map<String, Integer> treeMap = new TreeMap<>();

        // Add key-value pairs to the map
        treeMap.put("Ravi", 25);
        treeMap.put("Sita", 30);
        treeMap.put("Arjun", 22);
        treeMap.put("Lakshmi", 20);

        // Retrieve and print values using different keys
        System.out.println("Ravi: " + treeMap.get("Ravi"));
        System.out.println("Sita: " + treeMap.get("Sita"));

        // Iterate over the map using entry set
        System.out.println("Iterating over TreeMap:");
        for (Map.Entry<String, Integer> entry : treeMap.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }

        // Create a TreeMap with a custom comparator (descending order)
        Map<String, Integer> treeMapDescending = new TreeMap<>(Comparator.reverseOrder());

        // Add key-value pairs to the map
        treeMapDescending.put("Ravi", 25);
        treeMapDescending.put("Sita", 30);
        treeMapDescending.put("Arjun", 22);
        treeMapDescending.put("Lakshmi", 20);

        // Print the map
        System.out.println("TreeMap (Descending Order): " + treeMapDescending);
    }
}

Output:

Ravi: 25
Sita: 30
Iterating over TreeMap:
Arjun: 22
Lakshmi: 20
Ravi: 25
Sita: 30
TreeMap (Descending Order): {Sita=30, Ravi=25, Lakshmi=20, Arjun=22}

Conclusion

In this tutorial, we demonstrated how to use the TreeMap class in Java. We covered creating a TreeMap, adding and retrieving elements, iterating over the map, and using custom comparators. By following this guide, developers can effectively use TreeMap in scenarios where sorted order of keys is required.

Comments