Skip to content
Related Articles

Related Articles

Improve Article

How to iterate over a TreeMap in Java?

  • Last Updated : 28 Jun, 2021

Given a TreeMap, the task is to iterate this TreeMap in Java.

The TreeMap in Java is used to implement Map interface and NavigableMap along with the Abstract Class. We cannot iterate a TreeMap directly using iterators, because TreeMap is not a Collection.

So we will have to use TreeMap.entrySet() method. This method returns a collection-view(Set<Map.Entry>) of the mappings contained in this treemap. So we can iterate over key-value pair using getKey() and getValue() methods of Map.Entry. This method is most common and should be used if you need both map keys and values in the loop.

Below is the Java program to demonstrate it.

// Java program to iterate over a TreeMap
import java.util.Map;
import java.util.TreeMap;
class IterationDemo {
    public static void main(String[] arg)
        Map<String, String> gfg
            = new TreeMap<String, String>();
        // enter name/url pair
        gfg.put("GFG", "");
        gfg.put("Practice", "");
        gfg.put("Code", "");
        gfg.put("Quiz", "");
        // using for-each loop for
        // iteration over TreeMap.entrySet()
        for (Map.Entry<String, String>
                 entry : gfg.entrySet())
                "[" + entry.getKey()
                + ", " + entry.getValue() + "]");

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :