从嵌套可选检查中的列表中获取元素

kar*_*vai 2 java optional java-8

我有以下嵌套的空检查。试图通过使其可读,Optional但如何映射第一个元素?

卡在下面,不确定如何映射这条线

vo.getSomething().getAnother().get(0)
Run Code Online (Sandbox Code Playgroud)

我被困在三号线

Optional.of(vo.getSomething)
    .map(Something::getAnother)
    .map(List<Another>::get(0)) // will not work
Run Code Online (Sandbox Code Playgroud)

这是一个有效的空检查。我正在尝试使用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();
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

And*_*lko 5

Lambda表达式

.map(list -> list.get(0))
Run Code Online (Sandbox Code Playgroud)

应该管用。有些想法不能通过方法引用来表达。

List<Another>::get(0)虽然List<Another>::get可以,但不是有效的方法引用。

BiFunction<List<String>, Integer, String> function = List::get;
Run Code Online (Sandbox Code Playgroud)

该表达式的问题在于它具有一个常量0,您需要显式传递它。

但是,您可以编写一个静态方法

class ListFunctions {
    public static <T> T getFirst(List<? extends T> list) {
        return list.get(0);
    }
}
Run Code Online (Sandbox Code Playgroud)

并通过方法参考进行引用

.map(ListFunctions::getFirst)
Run Code Online (Sandbox Code Playgroud)