关于Map排序


在写项目的过程中,发现一个问题,就是在写Map后,对Map进行排序(倒序),在使用System.out.println输出是可以进行倒序的,但是如果再将结果放在Map作为返回值的时候顺序又变成无序的了。所以我就做了一下简单的处理,虽然可以有刚好的办法:

 

public class ZtMapSortUtil {
public static List<ApocalypseZtMapRO> getSortMap(Map<String , Integer> resultMap){
//通过ArrayList构造函数把map.entrySet()转换成list
List<Map.Entry<String,Integer>> list = new ArrayList<Map.Entry<String, Integer>>(resultMap.entrySet ());
//通过比较器实现比较排序
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o1.getValue().compareTo (o2.getValue()); //升序
// return o2.getValue().compareTo (o1.getValue()); //倒序
}
});
List<String> key = new ArrayList<String>();
List<Integer> num = new ArrayList<Integer>();
List<ApocalypseZtMapRO> sortMapROs = new ArrayList<ApocalypseZtMapRO>();
for(Map.Entry<String,Integer> mapping:list){
key.add(mapping.getKey());
num.add(mapping.getValue());
ApocalypseZtMapRO sortMapRO = new ApocalypseZtMapRO();
sortMapRO.setTeamName(mapping.getKey());
sortMapRO.setCount(mapping.getValue());
sortMapROs.add(sortMapRO);
}
/* for (int i = 0; i < list.size(); i++){
sortMapRO.setName(key.get(i));
sortMapRO.setNum(num.get(i));
sootMapROs.add(sortMapRO);
}*/
return sortMapROs;
}
}


这里就是使用一个list的方法,进行Map值的存放,然后按照一定的顺序取出来就可以。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM