【Java】List

对List中map集合中某个字段排序

升序排列

方法1

Collections.sort(maps, new Comparator<Map<String, Object>>() {
    @Override
    public int compare(Map<String, Object> o1, Map<String, Object> o2) {
        return o1.get("createtime").toString().compareTo(o2.get("createtime").toString());
    }
});

方法2

maps.sort((o1, o2) -> o1.get("createtime").toString().compareTo(o2.get("createtime").toString()));

方法3

maps.sort(Comparator.comparing(o -> o.get("createtime").toString()));

方法4

工具类
  • src/main/java/com/runsky/utils/MapComparatorAsc.java
package com.runsky.utils;

import java.util.Comparator;
import java.util.Map;

public class MapComparatorAsc implements Comparator<Map<String, Object>> {
    @Override
    public int compare(Map<String, Object> m1, Map<String, Object> m2) {
        Integer v1 = Integer.valueOf(m1.get("createtime").toString());
        Integer v2 = Integer.valueOf(m2.get("createtime").toString());
        if(v1 != null){
            return v1.compareTo(v2);
        }
        return 0;
    }
}
使用
  • src/main/java/com/runsky/sys/controller/DiydataController.java
Collections.sort(maps, new MapComparatorAsc());

结果

image

降序排列

工具类

  • src/main/java/com/runsky/utils/MapComparatorDesc.java
package com.runsky.utils;

import java.util.Comparator;
import java.util.Map;

public class MapComparatorDesc implements Comparator<Map<String, Object>> {
    @Override
    public int compare(Map<String, Object> m1, Map<String, Object> m2) {
        Integer v1 = Integer.valueOf(m1.get("createtime").toString());
        Integer v2 = Integer.valueOf(m2.get("createtime").toString());
        if (v2 != null) {
            return v2.compareTo(v1);
        }
        return 0;
    }
}

使用

  • src/main/java/com/runsky/sys/controller/DiydataController.java
Collections.sort(maps, new MapComparatorDesc());

结果

image

posted @ 2022-11-22 16:16  小魁jking  阅读(35)  评论(0编辑  收藏  举报