java List<Map> 排序

Collections的方式

1,升序排列(默认从小到大)

 public static void main(String[] args) {
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();

        list.add(getData(0));
        list.add(getData(7));
        list.add(getData(5));
        list.add(getData(6));
        list.add(getData(2));

        System.out.println("排序前" + list);

        Collections.sort(list, new Comparator<Map<String, String>>() {
            public int compare(Map<String, String> o1, Map<String, String> o2) {
                String str1 = o1.get("countScore").toString();
                String str2 = o2.get("countScore").toString();
                //str1在前,str2在后,默认升序,这里Integer类型的也可以
                return str1.compareTo(str2);
            
            }
        });
        System.out.println("排序后" + list);
    }

 private static Map<String, String> getData(int num) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("countScore", String.valueOf(num));
        return map;
    }

2,降序排列

  public static void main(String[] args) {
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();

        list.add(getData(0));
        list.add(getData(7));
        list.add(getData(5));
        list.add(getData(6));
        list.add(getData(2));

        System.out.println("排序前" + list);

        Collections.sort(list, new Comparator<Map<String, String>>() {
            public int compare(Map<String, String> o1, Map<String, String> o2) {
                String str1 = o1.get("countScore").toString();
                String str2 = o2.get("countScore").toString();
                //str2在前,str1在后,默认降序
                return str2.compareTo(str1);
            }
        });
        System.out.println("排序后" + list);
    }

    private static Map<String, String> getData(int num) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("countScore", String.valueOf(num));
        return map;
    }

foreach的方式

   listBrokenLines.forEach(ele->{
         ele.forEach((k, v) -> {
         if(Objects.equals(k,"name") && Objects.equals(v,"1号")){
                    int size = twofundList.size();
                    twofundList.add(size,ele);
                }
                if(Objects.equals(k,"name") && Objects.equals(v,"2号")){
                    int size = standardList.size();
                    standardList.add(size,ele);
            }
          });
      });

嵌套for的方式

  for (Map<String, Object> map : list) {
          for (Map.Entry<String, Object> m : map.entrySet()) {
              System.out.print("key:"+m.getKey() + "    ");
              System.out.println("value:"+m.getValue());
          }
      }

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值