从嵌套可选检查中的列表中获取元素
Get an element from a list in a Nested optional check
我有以下嵌套空值检查。试图通过 Optional
使其可读,但如何映射第一个元素?
卡在下面,不确定如何映射这条线
vo.getSomething().getAnother().get(0)
我卡在第3行了
Optional.of(vo.getSomething)
.map(Something::getAnother)
.map(List<Another>::get(0)) // will not work
这是一个有效的空值检查。我正在尝试使用 Optional 清理它。
if(vo.getSomething() != null){
if(vo.getSomething().getAnother() != null){
if(vo.getSomething().getAnother().get(0) != null){
if(vo.getSomething().getAnother().get(0).getInner() != null){
if(vo.getSomething().getAnother().get(0).getInner() != null){
if(vo.getSomething().getAnother().get(0).getInner().get(0) != null){
return vo.getSomething().getAnother().get(0).getInner().get(0).getProductName();
}
}
}
}
}
}
一个 lambda 表达式
.map(list -> list.get(0))
应该可以。有些想法不能用方法引用来表达。
List<Another>::get(0)
不是有效的方法参考,而 List<Another>::get
可以。
BiFunction<List<String>, Integer, String> function = List::get;
该表达式的问题是它有一个常量 0
,您需要显式传递它。
但是,您可以编写一个静态方法
class ListFunctions {
public static <T> T getFirst(List<? extends T> list) {
return list.get(0);
}
}
并通过方法引用来引用它
.map(ListFunctions::getFirst)
我有以下嵌套空值检查。试图通过 Optional
使其可读,但如何映射第一个元素?
卡在下面,不确定如何映射这条线
vo.getSomething().getAnother().get(0)
我卡在第3行了
Optional.of(vo.getSomething)
.map(Something::getAnother)
.map(List<Another>::get(0)) // will not work
这是一个有效的空值检查。我正在尝试使用 Optional 清理它。
if(vo.getSomething() != null){
if(vo.getSomething().getAnother() != null){
if(vo.getSomething().getAnother().get(0) != null){
if(vo.getSomething().getAnother().get(0).getInner() != null){
if(vo.getSomething().getAnother().get(0).getInner() != null){
if(vo.getSomething().getAnother().get(0).getInner().get(0) != null){
return vo.getSomething().getAnother().get(0).getInner().get(0).getProductName();
}
}
}
}
}
}
一个 lambda 表达式
.map(list -> list.get(0))
应该可以。有些想法不能用方法引用来表达。
List<Another>::get(0)
不是有效的方法参考,而 List<Another>::get
可以。
BiFunction<List<String>, Integer, String> function = List::get;
该表达式的问题是它有一个常量 0
,您需要显式传递它。
但是,您可以编写一个静态方法
class ListFunctions {
public static <T> T getFirst(List<? extends T> list) {
return list.get(0);
}
}
并通过方法引用来引用它
.map(ListFunctions::getFirst)