Collections排序List<Map>

之前做项目的是有些list的结果不知道怎么排序,后来从网上找到了这个方法,在put值的时候需要按照排序的类型添加。

public static void main(String[] args) {
        List<Map> list = new ArrayList<Map>();
        Map m1 = new HashMap<String, String>();
        m1.put("id", 1);
        m1.put("name", "刘备");
        Map m2 = new HashMap<String, String>();
        m2.put("id", 2);
        m2.put("name", "关羽");
        Map m3 = new HashMap<String, String>();
        m3.put("id",3);
        m3.put("name", "张飞");
        list.add(m2);
        list.add(m1);
        list.add(m3);
        System.out.println("初始化=============");
        for (Map map : list) {
            System.out.println(map.toString());
        }
        System.out.println("end");
        List<Map> result = process_intd(list, "id");
        System.out.println("result===================");
        for (Map map : result) {
            System.out.println(map.toString());
        }
        System.out.println("end");
    }

    // 按照int排序listMap--3  2 1 。
    public static List<Map> process_int(List<Map> data,final String arg) {
        List<Map> returnList = new ArrayList<Map>();
        List<Map> dsList = new ArrayList<Map>();
        Collections.sort(data, new Comparator<Map>() {
            public int compare(Map o1, Map o2) {
                return (Integer) o1.get(arg) > (Integer) o2.get(arg) ? ((Integer) o1
                        .get(arg) == (Integer) o2.get(arg) ? 0 : -1) : 1;
            }
        });
        returnList.addAll(data);
        return returnList;
    }

    // 123
    public static List<Map> process_intd(List<Map> data, final String arg) {
        List<Map> returnList = new ArrayList<Map>();
        Collections.sort(data, new Comparator<Map>() {
            public int compare(Map o1, Map o2) {
                return (Integer) o1.get(arg) < (Integer) o2.get(arg) ? ((Integer) o1
                        .get(arg) == (Integer) o2.get(arg) ? 0 : -1) : 1;
            }
        });
        returnList.addAll(data);
        return returnList;
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值