zoukankan      html  css  js  c++  java
  • 关于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值的存放,然后按照一定的顺序取出来就可以。
  • 相关阅读:
    POJ 1328 Radar Installation
    POJ 1700 Crossing River
    POJ 1700 Crossing River
    poj 3253 Fence Repair (贪心,优先队列)
    poj 3253 Fence Repair (贪心,优先队列)
    poj 3069 Saruman's Army(贪心)
    poj 3069 Saruman's Army(贪心)
    Redis 笔记与总结2 String 类型和 Hash 类型
    数据分析方法有哪些_数据分析方法
    数据分析方法有哪些_数据分析方法
  • 原文地址:https://www.cnblogs.com/April-Chou-HelloWorld/p/6635306.html
Copyright © 2011-2022 走看看