How to Get an Entryset from TreeMap in Java

This example shows how to retrieve all TreeMap key and value objects as a set of objects of type Entry. The class Entry has the getters methods to access the item's details. The method entrySet() returns all the elements as a set of objects.

You'll see that the entrySet() returns a set of Map.Entry< K,V> . What does it mean that from TreeMap< t1,t2> , you'll have a Set< Map.Entry< t1,t2> > and from that you can get the keys and values directly, or you can also go through a Iterator< Map.Entry< t1,t2> > and each element in Iterator is of type Map.Entry< t1,t2> . So, to get a key and its value, use these two methodsgetKey() and getValue().

import java.util.Iterator; 
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class entrySet {
public static void main(String args[]) {

TreeMap< String, Integer> treemap = new TreeMap< String, Integer> ();

treemap.put("A", 1);
treemap.put("B", 2);
treemap.put("C", 3);
treemap.put("D", 4);
treemap.put("E", 5);
treemap.put("F", 6);

//the entrySet() method returns a Set object of type Map.Entry< String, Integer>
Set< Map.Entry< String, Integer> > set = treemap.entrySet();

System.out.println("With Iterator");
//you can get an Iterator
Iterator it = set.iterator();
while(it.hasNext()){
Map.Entry me = (Map.Entry)it.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}

System.out.println("Without Iterator");
//or you can retrieve the key and its value directly without going through Iterator
for (Map.Entry< String, Integer> me : set) {
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
}
}
Output:

With Iterator
A: 1
B: 2
C: 3
D: 4
E: 5
F: 6
Without Iterator
A: 1
B: 2
C: 3
D: 4
E: 5
F: 6
References:
Coderanch: Iterator and EntrySet