对List集合里储存的map其中一个key的值,进行排序

1.对List集合里储存的map其中一个key的值,进行排序
   例:
 List<Map<String, Object>> list= new ArrayList();
注:list里面存在 name属性

//排序 倒序 对key为name 的值进行排序
if (!getList.isEmpty()) {
    Collections.sort(list, new Comparator<Map<String, Object>>() {
        @Override
        public int compare(Map<String, Object> o1, Map<String, Object> o2) {
            Integer o1Value = Integer.valueOf(o1.get("count").toString());
            Integer o2Value = Integer.valueOf(o2.get("count").toString());
            return o2Value.compareTo(o1Value);
        }
    });
}

//正序就把值反过来 : return o1Value.compareTo(o2Value);

2.还可以以流的形式进行排序,多字段进行排序

private static int comparator(Object o, Object o1) {
    Map map1 = Convert.convert(Map.class, o);
    Map map2 = Convert.convert(Map.class, o1);
    if (map1 == null && map2 == null)

        return 0;
    if (map1 == null || map2 == null) {

        throw new NullPointerException();
    }

    String name1 = (String) map1.get("name");

    String name2 = (String) map2.get("name");

    int c = name1.compareTo(name2);

    if (c != 0)

        return c;

    int age1 = (int) map1.get("age");

    int age2 = (int) map2.get("age");

    return age2 - age1;
}
public static void main(String[] args) {
    Map map = new HashMap();

    map.put("name", "张三");

    map.put("age", 22);

    Map map2 = new HashMap();

    map2.put("name", "李四");

    map2.put("age", 25);

    Map map3 = new HashMap();

    map3.put("name", "王五");

    map3.put("age", 26);

    Map map4 = new HashMap();

    map4.put("name", "钱七");

    map4.put("age", 28);

    List list = new ArrayList();

    list.add(map);

    list.add(map2);

    list.add(map3);

    list.add(map4);

    Stream stream = list.stream();

    List<Map>list2=(List<Map>)stream.sorted(Demo::comparator).collect(Collectors.toList());

    for (Map m : list2) {

        System.out.println(m.get("name") + " " + m.get("age"));

    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值