在利用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());
}
博客记录了Java中Map根据value大小进行排序的方法。先声明一个HashMap对象,再通过ArrayList构造函数将map.entrySet()转换成list,最后使用比较器进行比较排序,并遍历输出排序结果。
3148

被折叠的 条评论
为什么被折叠?



