lamda获取参数集合去空_仅当在Java8中使用lambda不为null时才过滤值

I have a list of objects say car. I want to filter this list based on some parameter using Java 8. But if the parameter is null, it throws NullPointerException. How to filter out null values?

Current code is as follows

requiredCars = cars.stream().filter(c -> c.getName().startsWith("M"));

This throws NullPointerException if getName() returns null.

解决方案

In this particular example I think @Tagir is 100% correct get it into one filter and do the two checks. I wouldn't use Optional.ofNullable the Optional stuff is really for return types not to be doing logic... but really neither here nor there.

I wanted to point out that java.util.Objects has a nice method for this in a broad case, so you can do this:

cars.stream()

.filter(Objects::nonNull)

Which will clear out your null objects. For anyone not familiar, that's the short-hand for the following:

cars.stream()

.filter(car -> Objects.nonNull(car))

To partially answer the question at hand to return the list of car names that starts with "M":

cars.stream()

.filter(car -> Objects.nonNull(car))

.map(car -> car.getName())

.filter(carName -> Objects.nonNull(carName))

.filter(carName -> carName.startsWith("M"))

.collect(Collectors.toList());

Once you get used to the shorthand lambdas you could also do this:

cars.stream()

.filter(Objects::nonNull)

.map(Car::getName) // Assume the class name for car is Car

.filter(Objects::nonNull)

.filter(carName -> carName.startsWith("M"))

.collect(Collectors.toList());

Unfortunately once you .map(Car::getName) you'll only be returning the list of names, not the cars. So less beautiful but fully answers the question:

cars.stream()

.filter(car -> Objects.nonNull(car))

.filter(car -> Objects.nonNull(car.getName()))

.filter(car -> car.getName().startsWith("M"))

.collect(Collectors.toList());

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值