java8 list中根据对象多属性去重

项目需求,需要使用 java8 实现 sql 里的 order 排序。使用 Comparator.comparing 和 thenComparing 实现

List shipList = new ArrayList<>();
List shipListTmp = new ArrayList<>();
Comparator byCustCd = Comparator.comparing(CnlEntity::getCustCd, Comparator.nullsLast(String::compareTo));
Comparator bySsd = Comparator.comparing(CnlEntity::getSsd, Comparator.nullsLast(Date::compareTo));
Comparator byGlobalNo = Comparator.comparing(e -> {
    if (StringUtils.isNotEmpty(e.getGlobalNo())) {
        if (e.getGlobalNo().length() > 6) {
            return e.getGlobalNo().substring(e.getGlobalNo().length() -6);
        } else {
            return e.getGlobalNo();
        }
    } else {
        return "";
    }
});
shipList = shipListTmp.stream().filter(entity -> StringUtils.equals(entity.getSubsidiaryCd(), "MJP"))
        .sorted(byCustCd.thenComparing(bySsd).thenComparing(byGlobalNo))
        .collect(Collectors.toList());

Comparator.nullsLast(String::compareTo) 可以防止 null 指针异常,遇到空数据排到最后。

你可能感兴趣的:(U-Java,java8,多属性去重,Comparator,comparing,thenComparing)