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 and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
- Program to Iterate over a Stream with Indices in Java 8
- How to iterate over a 2D list (list of lists) in Java
- How to iterate any Map in Java
- Stream iterate(T,Predicate,UnaryOperator) method in Java with examples
- Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
- Java.util.TreeMap.firstEntry() and firstKey() in Java
- Java.util.TreeMap.containskey() and containsValue() in Java
- Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
- Java.util.TreeMap.put() and putAll() in Java
- Java.util.TreeMap.floorEntry() and floorKey() in Java
- HashMap and TreeMap in Java
- Differences between TreeMap, HashMap and LinkedHashMap in Java
- TreeMap ceilingKey() in Java with Examples
- TreeMap ceilingEntry() and ceilingKey() methods in Java
- TreeMap containsValue() Method in Java
- TreeMap size() Method in Java
- TreeMap get() Method in Java
- TreeMap clone() Method in Java
- TreeMap containsKey() Method in Java
- TreeMap clear() Method in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.