How to Navigate a TreeMap in Java

The example above shows how to navigate through all the elements of a TreeMap. First, you can retrieve all the keys by calling the ketSet() which returns a list of keys as a set of objects. By reading each element of the set, you can retrieve the corresponding values from TreeMap.

import java.util.Set; 
import java.util.TreeMap;

public class Parcours_treemap {

public static void main(String a[]){
TreeMap< String, String> tm = new TreeMap< String, String> ();
//add key-value pairs
tm.put("first", "element1");
tm.put("second", "element2");
tm.put("third","element3");

Set< String> keys = tm.keySet();

for(String key: keys){
System.out.println("The value of "+key+" is: "+tm.get(key));
}
}
}
Running this code gives:

The value for second is: element2
The value for first is: element1
The value for third is: element3

Browse TreeMap using Iterator

In this example, we browse the TreeMpa list with Iterator and Map.Entry.

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

public class TreeMap_iterator {

public static void main(String a[]){
// Create a TreeMap
TreeMap< String, String> tmap = new TreeMap< String, String> ();

// Add key-value pairs to TreeMap
tmap.put("Key1","element1");
tmap.put("Key2","element2");
tmap.put("Key3","element3");
tmap.put("Key4","element4");

// Get all inputs
Set set = tmap.entrySet();

// Get iterator to browse the list
Iterator it = set.iterator();

// Show key-value peers
while(it.hasNext()) {
Map.Entry mentry = (Map.Entry)it.next();
System.out.print("key: "+mentry.getKey() + " - ");
System.out.println("Value: "+mentry.getValue());
}
}
}
This code returns this result after execution:

key: Key1 - Value: element1
key: Key2 - Value: element2
key: Key3 - Value: element3
key: Key4 - Value: element4

References:
Java Doc: Iterator
Java Doc: Map.Entry