(可选)获取字段 [英] Optionally getting field
问题描述
我有一个像这样的类结构:
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屋!