Welcome everyone

Comparator最佳实践

java 汪明鑫 188浏览 0评论
package pers.wmx.springbootfreemarkerdemo.util.comparator;

/**
 * @author wangmingxin03
 * Created on 2024-07-09
 */
public class UserModel {
    private long id;

    private String name;

    private long loginTime;

    private long createTime;

    private long updateTime;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public long getLoginTime() {
        return loginTime;
    }

    public void setLoginTime(long loginTime) {
        this.loginTime = loginTime;
    }

    public long getCreateTime() {
        return createTime;
    }

    public void setCreateTime(long createTime) {
        this.createTime = createTime;
    }

    public long getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(long updateTime) {
        this.updateTime = updateTime;
    }
}

排序

private static List<UserModel> sortUser(List<UserModel> users) {
        return users.stream()
                .filter(Objects::nonNull)
                .sorted(Comparator.comparing(UserModel::getUpdateTime, Comparator.reverseOrder())
                        .thenComparing(UserModel::getCreateTime)
                        .thenComparing(UserModel::getLoginTime, Comparator.reverseOrder())
                ).collect(Collectors.toList());
    }
  • 对应情况要返回 -1,0,1
  • 善用静态方法
java.util.Comparator#comparing
java.util.Comparator#comparingInt
java.util.Comparator#comparingLong
java.util.Comparator#comparingDouble
  • 多用基本类型的比较方法
com.google.common.primitives.Ints#compare
com.google.common.primitives.Longs#compare
com.google.common.primitives.Doubles#compare
com.google.common.primitives.Floats#compare
org.apache.commons.lang3.math.NumberUtils#compare
org.apache.commons.lang3.StringUtils#compare
  • 提前过滤空值
  • 建议使用reverseOrder(),而不是reversed()

转载请注明:汪明鑫的个人博客 » Comparator最佳实践

喜欢 (0)

说点什么

您将是第一位评论人!

提醒
avatar
wpDiscuz