仅当在Java8中使用lambda不为null时才过滤值 [英] Filter values only if not null using lambda in Java8

查看:8397
本文介绍了仅当在Java8中使用lambda不为null时才过滤值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象列表说 car 。我想基于使用Java 8的一些参数来过滤此列表。但是如果参数是 null ,它会抛出 NullPointerException 。如何过滤掉空值?

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?

当前代码如下

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

如果<$ c $,则抛出 NullPointerException c> getName()返回 null

This throws NullPointerException if getName() returns null.

推荐答案

在这个特定的例子中,我认为@Tagir是100%正确的,将它放入一个过滤器并进行两次检查。我不会使用 Optional.ofNullable 可选的东西实际上是返回类型不做逻辑......但实际上既不在这里也不在那里。

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.

我想指出 java.util.Objects 在广泛的情况下有一个很好的方法,所以你可以这样做:

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))

部分回答手头的问题以返回以M开头的汽车名称列表

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());

一旦习惯了简写的lambdas,你也可以这样做:

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());

不幸的是,一旦你 .map(Car :: getName)你只会返回名单而不是汽车。如此不那么漂亮但完全回答了这个问题:

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());

这篇关于仅当在Java8中使用lambda不为null时才过滤值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆