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;
public class TestMapSortByValue {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("d",4);
map.put("a",1);
map.put("c",3);
map.put("e",5);
map.put("b",2);
//排序前
System.out.println("before sort");
for(Map.Entry<String, Integer> entry:map.entrySet()){
System.out.println(entry.getKey()+"->"+entry.getValue());
}
System.out.println();
//将map转成list
List<Map.Entry<String, Integer>> infos = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
//对list排序,实现新的比较器
Collections.sort(infos, new Comparator<Map.Entry<String, Integer>>(){
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o1.getValue() - o2.getValue();
}
});
//申明新的有序 map,根据放入的数序排序
Map<String, Integer> lhm = new LinkedHashMap<String, Integer>();
//遍历比较过后的map,将结果放到LinkedHashMap
for(Map.Entry<String, Integer> entry:infos){
lhm.put(entry.getKey(), entry.getValue());
}
//遍历LinkedHashMap,打印值
System.out.println("after sort");
for(Map.Entry<String, Integer> entry:lhm.entrySet()){
System.out.println(entry.getKey()+"->"+entry.getValue());
}
}
}
before sort
d->4
e->5
b->2
c->3
a->1
after sort
a->1
b->2
c->3
d->4
e->5