How to iterate over a TreeMap in Java?


With the help of the AbstractMap Class, Java's TreeMap implements the Map interface and NavigableMap. This map is sorted using either the keys' inherent ordering or a Comparator that was provided when the map was created.

When working with a TreeMap in Java, the objective is to iterate via its elements. However, due to TreeMap not being a Collection, we cannot directly iterate over it using iterators.

Methods Used

To iterate through a TreeMap in Java, we need to utilize the TreeMap.entrySet() method. This function gives back a collection-view (SetMap.Entry>) of all the mappings that were saved in the TreeMap.

The key-value pairs can be accessed during iteration by using the getKey() and getValue() functions of the Map.Entry interface.

This approach is typical and advised when the keys and values of the map are needed in the loop.

TreeMap.entrySet()

To build a set with the same objects as the TreeMap, use the Java java.util.TreeMap.entrySet() method. We can access and work with the elements of the TreeMap in a set format because it basically returns a set view of the TreeMap. As an alternative, we might make a fresh set and add the TreeMap's components to it.

Syntax

tree_map.entrySet()

There are no parameters necessary for this technique. As a return value, the method returns a set that contains identical components as the TreeMap.

The getKey() and getValue() methods of the Map may be used to repeatedly iterate via the key-value pairs in a TreeMap in Java.interface for entry. When the map keys and values are required in the loop, this method is frequently used and advised.

getKey()

The code creates a TreeMap called "tlp" and adds some name/url pairs to it. Then, it uses a for-each loop to iterate over the entries in the TreeMap and prints each key-value pair.

Algorithm

  • Step 1 − Create a TreeMap called "tlp" to store the name/url pairs.

  • Step 2 − Add the name/url pairs to the TreeMap using the put() method.

  • Step 3 − We traverse through the entries in the TreeMap utilising the for-each loop.

  • Step 4 − For every entry, retrieve the key and value with the usage of the getKey() and getValue() functions of the Map.Entry interface.

  • Step 5 − With the help of System.out.println() function, we print the key-value pair.

Example

// Java program to iterate over a TreeMap

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

public class IterationExamplebyTLP {
   public static void main(String[] arg){
      Map<String, String> tlp
         = new TreeMap<String, String>();

      // enter name/url pair
      tlp.put("TLP", "tutorialspoint.com");
      tlp.put("Guide", "guide.tutorialspoint.com");
      tlp.put("For", "for.tutorialspoint.com");
      tlp.put("Students", "www.tutorialspoint.com");

      for (Map.Entry<String, String>
      entry : tlp.entrySet())
      System.out.println( "[" + entry.getKey() + ", " + entry.getValue() + "]");
   }
}

Output

[For, for.tutorialspoint.com]
[Guide, guide.tutorialspoint.com]
[Students, www.tutorialspoint.com]
[TLP, tutorialspoint.com]

entrySet()

The code creates a TreeMap object and adds 3 key-value pairs to it. Then, it iterates over the entries inside the TreeMap 3 different methods: a for-each loop, the forEach() method, and an iterator. The output of the code is the identical for all three methods.

Algorithm

  • Step 1 − Create a TreeMap object called "tm" to store key-value pairs of integers and strings.

  • Step 2 − Addition of some key-value pairs to the TreeMap with the help of the put() method.

  • Step 3 − Get the set of entries from the TreeMap with the help of the entrySet() method.

  • Step 4 − Traverse over the entries with the usage of a for-each loop, printing each key-value pair.

  • Step 5 − Print a blank line.

  • Step 6 − Use the forEach() method on the entries set to iterate over the entries again, printing each key-value pair.

  • Step 7 − Print a blank line.

  • Step 8 − Create an iterator for the entries set using the iterator() method.

  • Step 9 − Initialize a Map.Entry object called "entry" to save the current entry.

  • Step 10 − You must employ a while loop to iterate over the entries by using the iterator.

  • Step 11 − Within the loop, retrieve the key and value from the entry object. After that, print them.

  • Step 12 − The loop keeps on going until there are no more entries.

  • Step 13 − The program outputs the key-value pairs in the TreeMap.

Example

// Java Program to Traverse Over Entries in a TreeMap

import java.util.*;

public class TLP {

   // Main driver method
   public static void main(String[] args){

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

      tm.put(1, "Tutorialspoint");
      tm.put(2, "Code");
      tm.put(3, "Guide");

      Set<Map.Entry<Integer, String> > entries
      = tm.entrySet();

      for (Map.Entry<Integer, String> entry : entries) {
         System.out.println(entry.getKey() + "=" + entry.getValue());
      }

      System.out.println();

      entries.forEach(entry -> {
         System.out.println(entry.getKey() + "=" + entry.getValue());
      });

      System.out.println();

      Iterator<Map.Entry<Integer, String> > iterator
         = entries.iterator();

      Map.Entry<Integer, String> entry = null;

      while (iterator.hasNext()) {
         entry = iterator.next();
         System.out.println(entry.getKey() + "=" + entry.getValue());
      }
   }
}

Output

1=Tutorialspoint
2=Code
3=Guide

1=Tutorialspoint
2=Code
3=Guide

1=Tutorialspoint
2=Code
3=Guide

Conclusion

With regards to iterating over a TreeMap in Java, there are a few key methods to keep in mind. The TreeMap class, which implements the Map interface and NavigableMap, allows for sorting based on keys or a provided Comparator.

We must utilise the TreeMap, though, as it is not a Collection.To iterate through its elements, use the entrySet() method. We may obtain the key-value pairs during iteration by using the Map.Entry interface's getKey() and getValue() methods.

Updated on: 18-Oct-2023

466 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements