java8 根据list map中某个字段排序

2022-10-13  本文已影响0人  writeanewworld

示例1:(字段为金额相关等浮点型)

 public static void main(String[] args) {
    List<Map<String, Object>> resList = new ArrayList<>();
    Map<String, Object> valueMap = new HashMap<>();
    valueMap.put("storeCDAndName", "12" + "-" + "测试");
    valueMap.put("storeSale", "100.11");
    valueMap.put("sample", false);

    Map<String, Object> valueMap1 = new HashMap<>();
    valueMap1.put("storeCDAndName", "121" + "-" + "测试111");
    valueMap1.put("storeSale", "10.2");
    valueMap1.put("sample", false);


    Map<String, Object> valueMap2 = new HashMap<>();
    valueMap2.put("storeCDAndName", "123122" + "-" + "31232");
    valueMap2.put("storeSale", "1000");
    valueMap2.put("sample", false);

    resList.add(valueMap);
    resList.add(valueMap1);
    resList.add(valueMap2);

    List<Map> collect =
            resList.stream().sorted((o1, o2) -> -Double.compare(Double.parseDouble(o1.get("storeSale").toString()), Double.parseDouble(o2.get("storeSale").toString())))
                    .collect(Collectors.toList());


    System.out.println(collect);

  }

示例2: 字段为 整型 或者 字符串类型

  方式1: wctList.sort((o1, o2) -> o1.get("shelfNum").toString().compareTo(o2.get("shelfNum").toString()));
  方式2: wctList.sort(Comparator.comparing(o -> o.get("shelfNum").toString()));

上一篇下一篇

猜你喜欢

热点阅读