How to Iterate TreeMap : TreeMap Iterator Example

I have already shared how TreeMap works in java. In this post we will see how to iterate TreeMap in java.We will iterate TreeMap using Iterator and Map.Entry.

Read Also :  Java Collection Interview Questions


TreeMap Iterator Example



import java.util.*;

 public class TreeMapIteratorExample {
    public static void main(String args[]) {
        
    // Declaring a TreeMap of String keys and String values
    TreeMap<String, String> treemap = new TreeMap<String, String>();
    // Add Key-Value pairs to TreeMap
    treemap.put("Key1", "Pear");
    treemap.put("Key2", "Apple");
    treemap.put("Key3", "Orange");
    treemap.put("Key4", "Papaya");
    treemap.put("Key5", "Banana");
    
    
    // Get Set of entries
    Set set = treemap.entrySet();
    // Get iterator
    Iterator it = set.iterator();
    // Show TreeMap elements
    System.out.println("TreeMap contains: ");
    while(it.hasNext()) {
      Map.Entry pair = (Map.Entry)it.next();
      System.out.print("Key is: "+pair.getKey() + " and ");
      System.out.println("Value is: "+pair.getValue());
    }
  }
}


Output
TreeMap contains: 
Key is: Key1 and Value is: Pear
Key is: Key2 and Value is: Apple
Key is: Key3 and Value is: Orange
Key is: Key4 and Value is: Papaya
Key is: Key5 and Value is: Banana

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry