How to iterate over a TreeMap in Java?
Given a TreeMap, the task is to iterate this TreeMap in Java.
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.
[Code, code.geeksforgeeks.org] [GFG, geeksforgeeks.org] [Practice, practice.geeksforgeeks.org] [Quiz, quiz.geeksforgeeks.org]
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.