java8 stream排序空字段排在前面或后面

直接粗暴sorted会NPE,这种写法可以避免

list.stream().sorted(Comparator.comparing(l -> l.getCreateTime(), Comparator.nullsFirst(Date::compareTo))).collect(toList());
toOrderList.stream().sorted(Comparator.comparing(l -> l.getContractCode(), Comparator.nullsFirst(String::compareTo))).collect(toList());

java8根据某字段顺序和倒序排列

顺序

resultList.stream().sorted(Comparator.comparing(Role::getCreateTime)).collect(Collectors.toList());

倒序

resultList.stream().sorted(Comparator.comparing(Role::getCreateTime).reversed()).collect(Collectors.toList());

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。