List集合按指定字段排序两种实现核心代码

一、
Collections.sort(目标List, new Comparator<目标List中的类>() {

    @Override
    public int compare(目标List中的类 o1, 目标List中的类 o2) {
        // 升序排列// 降序排序
        if (o1.get用于排序属性() > o2.get用于排序属性()) {
            return 1;// -1
        }
        if (o1.get用于排序属性() == o2.get用于排序属性()) {
            return 0;
        }
        return -1;// 1
    }
});

二、也可以 目标类 implements Comparator<目标类>,然后实现compare方法,如:

@Override
public int compare(目标类 o1, 目标类 o2) {

    // 升序排列// 降序排序
    if (o1.get用于排序属性() > o2.get用于排序属性()) {
        return 1;// -1
    }
    if (o1.get用于排序属性() == o2.get用于排序属性()) {
        return 0;
    }
    return -1;// 1
    
}

然后直接在需要排序的地方调用:

Collections.sort(目标List, new 目标类());
发布了65 篇原创文章 · 获赞 8 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/u012382791/article/details/99822037
今日推荐