Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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
TreeMapString, String> treemap = new TreeMapString, 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


This post first appeared on Java Hungry, please read the originial post: here

Share the post

How to Iterate TreeMap : TreeMap Iterator Example

×

Subscribe to Java Hungry

Get updates delivered right to your inbox!

Thank you for your subscription

×