可选的获取字段 [英] Optional Getting Field

查看:143
本文介绍了可选的获取字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的类结构:

public class Foo {
    private FooB foob;

    public Optional<FooB> getFoob() {
        return Optional.ofNullable(foob);
    }
}

public class FooB {
    private int valA;

    public int getValA() {
        return valA;
    }
}

我的目标是为<$调用get方法c $ c> fooB 然后检查它是否存在。如果它存在则返回 valA 属性,如果不存在则返回null。所以类似这样:

My objective is to call the get method for fooB and then check to see if it's present. If it is present then return the valA property, if it doesn't then just return null. So something like this:

Integer valA = foo.getFoob().ifPresent(getValA()).orElse(null);

当然这不是正确的Java 8可选语法,而是我的伪代码。有没有办法在Java 8中用1行实现这个目的?

Of course this isn't proper Java 8 optional syntax but that's my "psuedo code". Is there any way to achieve this in Java 8 with 1 line?

推荐答案

你所描述的是 map 方法:

What you are describing is the map method:

Integer valA = foo.getFoob().map(f -> f.getValA()).orElse(null);

map 可让您转换内部的值可选如果值存在则带有函数,并且只有在不存在的值时才更改可选的类型。

map lets you transform the value inside an Optional with a function if the value is present, and only changes the type of the optional if the value in not present.

另请注意,您可以从映射函数返回null,在这种情况下,结果将是 Optional.empty()

Note also that you can return null from the mapping function, in which case the result will be Optional.empty().

这篇关于可选的获取字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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