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.
[Code, code.geeksforgeeks.org] [GFG, geeksforgeeks.org] [Practice, practice.geeksforgeeks.org] [Quiz, quiz.geeksforgeeks.org]
Now let us see traversal over the entries in the TreeMap object. In order to implement, we are considering very simple map elements associativity where we are having three elements say they be “Geeks”, “for”, “Geeks” and be the key value ‘1’, ‘2’ and ‘3’ of integer type. So from this only we are able to get we need to make an object of TreeMap class.
1->Geeks 2->For 3->Geeks 1->Geeks 2->For 3->Geeks 1->Geeks 2->For 3->Geeks