import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class TestMapSortByKey {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(4,"d");
map.put(1,"a");
map.put(3,"c");
map.put(5,"e");
map.put(2,"b");
//before sort
System.out.println("before sort");
for(Map.Entry<Integer, String> entry:map.entrySet()){
System.out.println(entry.getKey()+"->"+entry.getValue());
}
System.out.println();
//map to list,params must be map.entrySet();
List<Map.Entry<Integer, String>> infos = new ArrayList<Map.Entry<Integer, String>>(map.entrySet());
//sort by key
Collections.sort(infos, new Comparator<Map.Entry<Integer, String>>(){
@Override
public int compare(Entry<Integer, String> o1, Entry<Integer, String> o2) {
return o1.getKey()-o2.getKey();
}
});
Map<Integer, String> lhm = new LinkedHashMap<Integer, String>();
for(Map.Entry<Integer, String> entry:infos){
lhm.put(entry.getKey(), entry.getValue());
}
//遍历LinkedHashMap,打印值
System.out.println("after sort");
for(Map.Entry<Integer, String> entry:lhm.entrySet()){
System.out.println(entry.getKey()+"->"+entry.getValue());
}
}
}
before sort
1->a
2->b
3->c
4->d
5->e
after sort
1->a
2->b
3->c
4->d
5->e