Sunday, November 17, 2024
Google search engine
HomeLanguagesJavaHow to iterate over a TreeMap in Java?

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. 

Example 1:

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", "www.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, www.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 differentiate 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 differentiate 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 getKey() 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
RELATED ARTICLES

Most Popular

Recent Comments