【问题标题】:Get an element from a list in a Nested optional check从嵌套可选检查中的列表中获取元素
【发布时间】:2019-09-17 10:23:58
【问题描述】:

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

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

vo.getSomething().getAnother().get(0)

我卡在第三行

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

【问题讨论】:

  • @OleksandrPyrohov 接受的答案正是 OP 正在做什么,所以我认为他们知道这种方法。问题是关于如何使List&lt;Another&gt;::get(0) 工作
  • 这种糟糕的设计不应该由Optional 来解决,而应该通过重构所有的嵌套来解决。
  • @Kayaman 我们如何重构它......这是从外部 api 在该结构中捕获的 json 响应......
  • @karvai 几种方式。您不认为只为了获得一个产品名称而进行 6 次空检查不是最佳选择吗?

标签: java java-8 optional


【解决方案1】:

一个 lambda 表达式

.map(list -> list.get(0))

应该可以。有些想法无法通过方法引用来表达。

List&lt;Another&gt;::get(0) 不是有效的方法引用,而 List&lt;Another&gt;::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)

【讨论】:

    猜你喜欢
    • 2015-10-15
    • 2023-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2023-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多