(可选)获取字段 [英] Optionally getting field

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

问题描述

我有一个像这样的类结构:

I have a class structure like this:

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;
    }
}

我的目标是为fooB调用get方法,然后检查它是否存在.如果存在,则返回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 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?

推荐答案

您所描述的是

What you are describing is the map method:

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

map允许您使用函数在Optional内部转换值,如果该值不存在,则仅更改可选类型.

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