2008年3月26日 星期三

[JAVA] Sorting HashMap base on Key

Question:
How to sort a hashmap using its key?

Answer:
Dump the HashMap into a TreeMap

Map yourMap= new HashMap();
// put some tuples in yourMap ...
Map sortedMap = new TreeMap(yourMap);

Example:
import java.util.*;

public class Test{

public static void main(String args[]){
Map map = new HashMap();
map.put("key3", "value1");
map.put("key1", "value2");
map.put("key2", "value3");
Map sortedMap = new TreeMap(map);
System.out.println(sortedMap);
}
}

沒有留言: