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

查看:14
本文介绍了仅当在 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"));

如果 getName() 返回 null,则抛出 NullPointerException.

This throws NullPointerException if getName() returns null.

推荐答案

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

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天全站免登陆