How to iterate through TreeMap

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

public class TreeMapIterate {

public static void main(String[] args) {

Map<Integer, String> tm = new TreeMap<Integer,String>();

// add key and values
tm.put(1,”java”);
tm.put(2,”cpp”);
tm.put(3,”php”);
tm.put(4,”c”);
tm.put(5, “mysql”);

//Returns a Set view of the keys contained in this map

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

for (Integer key : keys) {
System.out.println(” key =”+key+” value =”+tm.get(key));
}

}

}

Output:

key =1 value =java

key =2 value =cpp

key =3 value =php

key =4 value =c

key =5 value =mysql

 

Leave a Reply

Your email address will not be published. Required fields are marked *

8 + 1 =