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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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", "geeksforgeeks.org");
        gfg.put("Practice", "practice.geeksforgeeks.org");
        gfg.put("Code", "code.geeksforgeeks.org");
        gfg.put("Quiz", "quiz.geeksforgeeks.org");
  
        // using for-each loop for
        // iteration over TreeMap.entrySet()
        for (Map.Entry<String, String>
                 entry : gfg.entrySet())
            System.out.println(
                "[" + entry.getKey()
                + ", " + entry.getValue() + "]");
    }
}

chevron_right


Output:

[Code, code.geeksforgeeks.org]
[GFG, geeksforgeeks.org]
[Practice, practice.geeksforgeeks.org]
[Quiz, quiz.geeksforgeeks.org]

java-img

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 contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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 contribute@geeksforgeeks.org to report any issue with the above content.