Open In App

How to Create a TreeMap in Java and Add Key-Value Pairs in it?

Last Updated : 08 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, a TreeMap maintains elements in a sorted order as it is an implementation of the SortedMap Interface. It stores key-value pairs in a sorted order. In this article, we will explore the creation of TreeMap in Java and learn the step-by-step process of adding key-value pairs.

Program to Create and Add Key-Value Pairs to a TreeMap in Java

Below is an example of how to create and after that how to add key-value pairs in a TreeMap.

1. Creating a TreeMap

Java




// Java program to create a TreeMap
import java.util.TreeMap;
public class TreeMapExample {
  
    public static void main(String[] args) {
        // Creating a TreeMap
        TreeMap<String, Integer> numberMap = new TreeMap<>();
  
        // Adding key-value pairs
        numberMap.put("One", 1);
        numberMap.put("Two", 2);
        numberMap.put("Three", 3);
  
        // Displaying the TreeMap
        System.out.println("TreeMap: " + numberMap);
    }
}


Output

TreeMap: {One=1, Three=3, Two=2}

Explanation of the Program:

  • In the above program, tt imports the TreeMap class from the java.util package.
  • It defines a class named TreeMapExample.
  • Inside the main method:
    • It creates a TreeMap named numberMap with keys of type String and values of type Integer.
    • Key-value pairs are added to the numberMap.
    • The contents of the numberMap are displayed.

2. Adding Key-Value Pairs:

Java




// Java program to add key-value pairs in a TreeMap
import java.util.TreeMap;
public class TreeMapExample {
  
    public static void main(String[] args) {
        // Creating a TreeMap
        TreeMap<String, String> fruitMap = new TreeMap<>();
  
        // Adding key-value pairs
        fruitMap.put("Strawberry", "Red");
        fruitMap.put("Banana", "Yellow");
        fruitMap.put("Kiwi", "Green");
  
        // Displaying the TreeMap
        System.out.println("Fruit TreeMap: " + fruitMap);
    }
}


Output

Fruit TreeMap: {Banana=Yellow, Kiwi=Green, Strawberry=Red}

Explanation of the Program:

  • In the above program, it imports the TreeMap class from the java.util package.
  • It defines a class named TreeMapExample.
  • Inside the main method:
    • It creates a TreeMap named fruitMap with keys and values of type String.
    • Key-value pairs representing fruits and their colors are added to the fruitMap.
    • The contents of the fruitMap are displayed.z


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads