在利用map时,偶尔需要根据value的大小来进行排序,今天就遇到了。现在就把map根据value进行排序的方法在此记录。
1、声明一个hashmap对象Map map = new HashMap();
2、通过ArrayList构造函数把map.entrySet()转换成list
List> mappingList = new ArrayList>(map.entrySet());
3、通过比较器进行比较排序Collections.sort(mappingList, new Comparator>(){
public int compare(Map.Entry mapping1,Map.Entry mapping2){
return mapping1.getKey().compareTo(mapping2.getKey());
}
});
for(Map.Entry mapping:mappingList){
System.out.println(mapping.getKey()+":"+mapping.getValue());
}