Lambda表达式排序,出现空指针异常:

当使用Lambda表达式对对象集合按特定属性排序时,若该属性可能出现null值,会导致空指针异常。解决方案是利用Comparator的nullsFirst和nullsLast方法,确保在比较时正确处理null值。通过示例代码展示了如何实现。
摘要由CSDN通过智能技术生成

问题描述:对象集合中,根据对象的某个属性进行升降排序时,未考虑对应属性的null值,导致出现空指针异常。
解决方法Comparator.nullsFirstComparator.nullsLast

List<User> nList = list.stream().sorted(
    Comparator.comparing(User::getCode, Comparator.nullsFirst(String::compareTo)))
    .collect(Collectors.toList());

下见源码

 /**
     * Returns a null-friendly comparator that considers {@code null} to be
     * less than non-null. When both are {@code null}, they are considered
     * equal. If both are non-null, the specified {@code Comparator} is used
     * to determine the order. If the specified comparator is {@code null},
     * then the returned comparator considers all non-null values to be equal.
     *
     * <p>The returned comparator is serializable if the specified comparator
     * is serializable.
     *
     * @
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值