How to create TreeMap program in java

import java.util.*;

class TreeMap_TechSarvam 
{
    public static void main(String args[]) 
    {
        // Creating a TreeMap
        TreeMap<Integer, String> hm = new TreeMap<Integer, String>();

        // Adding elements to the TreeMap
        hm.put(100, "Amit");
        hm.put(102, "Ravi");
        hm.put(101, "Vijay");
        hm.put(103, "TechSarvam");

        // Iterating through the TreeMap
        for (Map.Entry<Integer, String> m : hm.entrySet()) 
        {
            System.out.println(m.getKey() + " " + m.getValue());
        }
    }
}

Step-by-Step Explanation:

Let’s understand the code in detail, along with the output that is to be generated. Let’s follow step by step.

1. Importing Required Classes:

import java.util.*;

The java.util.* package is imported because various utility classes like TreeMap, Map.Entry and other collection classes are used here in this program.

2. Class Declaration:

class TreeMap_TechSarvam {

The declaration of this class is such that the ‘main()’ function, that in fact represents a starting point to a program can be contained as part of its structure.

3. Main Method:

public static void main(String args[]) {

}

The main() function is the entry point of Java program. The code inside this function is executed when this program is run.

4. Creating a TreeMap Instance:

TreeMap<Integer, String> hm = new TreeMap<Integer, String>();

  • A TreeMap object named hm is created. A TreeMap is a Map implementation based on a red-black tree. It sorts keys in ascending order according to the natural ordering of its keys, or by a Comparator provided at map creation time, if any.
  • The map is parameterized with <Integer, String>, meaning the keys are of type Integer and the values are of type String.

5. Adding Key-Value Pairs:

hm.put(100, “Amit”);

hm.put(102, “Ravi”);

hm.put(101, “Vijay”);

hm.put(103, “TechSarvam”);

The put() method is used to add key-value pairs to the TreeMap:

  • Key 100 is mapped to value \”Amit\”.
  • Key 102 is mapped to the value \”Ravi\”.
  • Key 101 is mapped to the value \”Vijay\”.
  • Key 103 is mapped to the value \”TechSarvam\”.

Since a TreeMap sorts its keys by default in ascending order, the keys are sorted before they are stored.

6. Iterating Over the TreeMap:

for (Map.Entry m : hm.entrySet()) {

      System.out.println(m.getKey() + ” ” + m.getValue());

  }

  •  hm.entrySet(): returns a Set of entries from the TreeMap. The entry itself is of the form Map.Entry.
  • for (Map.Entry m : hm.entrySet()): A loop to step over all elements from the Set in turn and gets the corresponding key and the corresponding value with this code statement, m.getKey () retrieves the key.
  • m.getvalue() is the value.
  • System.out.println(m.getKey() + ” ” + m.getvalue()) prints every entry with a new line in-between.

7. Output:

As TreeMap internally sorts its keys in ascending order, entries will be printed in ascending order of the keys.

 Sorted Order (by keys):

100 Amit

101 Vijay

102 Ravi

103 TechSarvam

Key Concepts:

1. TreeMap:

  • TreeMap is an implementation of the Map interface that sorts the keys in natural order or by a comparator, if given. It ensures that the keys are arranged in ascending order while in iteration over the map.
  • Unlike HashMap, which does not guarantee any specific order of the elements, TreeMap keeps the keys sorted.

2. put() Method:

The put() method is used to insert a key-value pair into the map. If the key already exists in the map, it will update the value associated with the key.

3. entrySet() Method:

The entrySet() method returns a Set view of the entries in the map. This Set includes each entry that is a Map.Entry object, meaning it contains both the key and the value.

4. Iterating with for-each loop:

An enhanced for loop will go over the set of entries. For each Map.Entry, you would refer to the key by using m.getKey() and to the value by using m.getValue()

Time Complexity:

  • Insertion (put()): O(log n), with n being the number of elements in the map, since TreeMap is based on a red-black tree, whose insertion operations result in a log(n) time complexity.
  • Iteration (entrySet() and for-each loop): O(n), with n as the number of entries in the map. Linear time is the time complexity in iterating over all entries in a map.

This program shows how to use TreeMap to keep key-value pairs sorted by their keys. The keys are initially sorted in ascending order, and the program prints each key-value pair in the sorted order. The output of this program is deterministic due to the automatic ordering provided by the TreeMap object.

Leave a Comment

Your email address will not be published. Required fields are marked *