I have a Map that has strings for both keys and values.
Data is like following:
\"question1\", \"1\"
\"question9\", \"1\"
\"que
If you already have a map and would like to sort it on keys, simply use :
Map treeMap = new TreeMap(yourMap);
A complete working example :
import java.util.HashMap;
import java.util.Set;
import java.util.Map;
import java.util.TreeMap;
import java.util.Iterator;
class SortOnKey {
public static void main(String[] args) {
HashMap hm = new HashMap();
hm.put("3","three");
hm.put("1","one");
hm.put("4","four");
hm.put("2","two");
printMap(hm);
Map treeMap = new TreeMap(hm);
printMap(treeMap);
}//main
public static void printMap(Map map) {
Set s = map.entrySet();
Iterator it = s.iterator();
while ( it.hasNext() ) {
Map.Entry entry = (Map.Entry) it.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();
System.out.println(key + " => " + value);
}//while
System.out.println("========================");
}//printMap
}//class