针对List《Map《String,Object》》多条件组合排序

需求: 对List<Map<String,Object>> 中map的value进行多字段组合排序

话不多说, 直接上代码:

public static void main(String[] args) {

        List<Map<String,Object>> list = new ArrayList<>();
        Map<String, Object> map1 = new HashMap<>();
        map1.put("id","1");
        map1.put("code","1234");
        map1.put("score",90);
        map1.put("rate","88%");
        list.add(map1);
        Map<String, Object> map2 = new HashMap<>();
        map2.put("id","2");
        map2.put("code","2345");
        map2.put("score",70);
        map2.put("rate","60%");
        list.add(map2);
        Map<String, Object> map3 = new HashMap<>();
        map3.put("id","3");
        map3.put("code","3456");
        map3.put("score",70);
        map3.put("rate","50%");
        list.add(map3);
        Map<String, Object> map4 = new HashMap<>();
        map4.put("id","4");
        map4.put("code","4567");
        map4.put("score",80);
        map4.put("rate","90%");
        list.add(map4);
        Map<String, Object> map5 = new HashMap<>();
        map5.put("id","5");
        map5.put("code","5678");
        map5.put("score",88);
        map5.put("rate","80%");
        list.add(map5);

        Collections.sort(list, new Comparator<Map<String,Object>>() {

            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                String score1 = String.valueOf(o1.get("score"));
                String score2 = String.valueOf(o2.get("score"));
                int c = score1.compareTo(score2);
                if(c != 0)
                    return c;

                String i1 = String.valueOf(o1.get("id"));
                String i2 = String.valueOf(o2.get("id"));
                return i1.compareTo(i2);
            }
        });

        System.out.println(list.toString());

    }

结果:

排序前: [{score=60, code=1234, rate=88%, id=1}, {score=70, code=2345, rate=60%, id=2}, {score=70, code=3456, rate=50%, id=3}, {score=60, code=4567, rate=90%, id=4}, {score=88, code=5678, rate=80%, id=5}]
排序后: [{score=60, code=1234, rate=88%, id=1}, {score=60, code=4567, rate=90%, id=4}, {score=70, code=2345, rate=60%, id=2}, {score=70, code=3456, rate=50%, id=3}, {score=88, code=5678, rate=80%, id=5}]

先对score进行升序排序, 相同分数则对id进行升序排序.

若想进行降序排序, 则只需把compareTo两边的参数互换即可; 

仅供参考!

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值