Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to iterate over a TreeMap in Java?

  • Last Updated : 31 Oct, 2021

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. 

Example 1:

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.

Java




// 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() + "]");
    }
}
Output: 
[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.

Example 2:

Java




// Java Program to Iterate Over Entries in a TreeMap
 
import java.util.*;
 
// Importing required
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating a TreeMap class object
        // Objects are of key-value pairs (integer and
        // string type)
        TreeMap<Integer, String> tm
            = new TreeMap<Integer, String>();
 
        // Customly adding elements
        tm.put(1, "Geeks");
        tm.put(2, "For");
        tm.put(3, "Geeks");
 
        //  Get all entries using the entrySet() method
        Set<Map.Entry<Integer, String> > entries
            = tm.entrySet();
 
        // Way 1
        // Using for loops
        for (Map.Entry<Integer, String> entry : entries) {
            System.out.println(entry.getKey() + "->"
                               + entry.getValue());
        }
 
        // New line to differenciate differences in output
        // between for loop and for each loop
        System.out.println();
 
        // Way 2 - getting code shorter and simpler
        // For each loops
 
        entries.forEach(entry -> {
            System.out.println(entry.getKey() + "->"
                               + entry.getValue());
        });
 
        // New line to differenciate differences in output
        // between for each loop and iterator traversal
        System.out.println();
 
        // Way 3 - New way to
        // Getting an iterator
        Iterator<Map.Entry<Integer, String> > iterator
            = entries.iterator();
 
        // Additional step here
        // To Initialize object holding for
        // key-value pairs to null
        Map.Entry<Integer, String> entry = null;
 
        // Holds true till there is no element remaining in
        // the object using hasNExt() method
        while (iterator.hasNext()) {
 
            // Moving onto next pairs using next() method
            entry = iterator.next();
 
            // Printing the key-value pairs
            // using getKet() and getValue() methods
            System.out.println(entry.getKey() + "->"
                               + entry.getValue());
        }
    }
}
Output
1->Geeks
2->For
3->Geeks

1->Geeks
2->For
3->Geeks

1->Geeks
2->For
3->Geeks



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!