How to iterate over a TreeMap in Java?

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 and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at to report any issue with the above content.