TreeMap with Looping
We can iterate TreeMap using enhanced for loop with keyset() method or by using enhanced for loop with EntrySet method or by using iterator
Case 1
Enhanced for loop with keyset()
Example
- import java.util.*;
- public class TreeMapEnhancedForLoopExample {
- public static void main(String args[]) {
- TreeMap<Integer,String> tm = new TreeMap<>();
- tm.put(3, “Three”);
- tm.put(1, “One”);
- tm.put(2, “Two”);
- Set<Integer> keys = tm.keySet();
- for(Integer key: keys){
- System.out.println(“Value of “+key+” is: “+tm.get(key));
- }
- }
- }
import java.util.*;
public class TreeMapEnhancedForLoopExample {
public static void main(String args[]) {
TreeMap<Integer,String> tm = new TreeMap<>();
tm.put(3, “Three”);
tm.put(1, “One”);
tm.put(2, “Two”);
Set<Integer> keys = tm.keySet();
for(Integer key: keys){
System.out.println(“Value of “+key+” is: “+tm.get(key));
}
}
}
In this program, We have accessed all the keys of TreeMap using keySet( ) method and then iterated all the keys using enhanced for loop and accessed value by passing key in each iteration in the loop.
Case 2
Enhanced for loop with entrySet()
Example
- import java.util.*;
- public class TreeMapEnhancedForLoopEntrySetExample {
- public static void main(String args[]) {
- TreeMap<Integer,String> tm = new TreeMap<>();
- tm.put(2, “Two”);
- tm.put(1, “One”);
- tm.put(3, “Three”);
- for (Map.Entry entry : tm.entrySet()) {
- Integer key = entry.getKey();
- Object value = entry.getValue();
- System.out.println(“Value of “+key+” is: “+value);
- }
- }
- }
import java.util.*;
public class TreeMapEnhancedForLoopEntrySetExample {
public static void main(String args[]) {
TreeMap<Integer,String> tm = new TreeMap<>();
tm.put(2, “Two”);
tm.put(1, “One”);
tm.put(3, “Three”);
for (Map.Entry entry : tm.entrySet()) {
Integer key = entry.getKey();
Object value = entry.getValue();
System.out.println(“Value of “+key+” is: “+value);
}
}
}
Case 3
Using iterator
Example
- import java.util.*;
- public class TreeMapIteratorExample {
- public static void main(String args[]) {
- TreeMap<Integer,String> tm = new TreeMap<>();
- tm.put(3, “Three”);
- tm.put(1, “One”);
- tm.put(2, “Two”);
- Iterator it = tm.entrySet().iterator();
- while (it.hasNext()) {
- Map.Entry pair = (Map.Entry)it.next();
- System.out.println(pair.getKey() + ” = ” + pair.getValue());
- }
- }
- }
import java.util.*;
public class TreeMapIteratorExample {
public static void main(String args[]) {
TreeMap<Integer,String> tm = new TreeMap<>();
tm.put(3, “Three”);
tm.put(1, “One”);
tm.put(2, “Two”);
Iterator it = tm.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + ” = ” + pair.getValue());
}
}
}

