gpt4 book ai didi

java - 在每次方法调用后检查对象是否为空

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:06:47 24 4
gpt4 key购买 nike

我有一个简单的片段,我想以更优雅的方式重新设计它,也许可以使用最新的 JDK 8 功能:

String x = methodCall();
if(x==null) {x=method2();}
if(x==null) {x=method3();}
if(x==null) {x=method4();}

// doing calculation with X

最佳答案

您可以使用流:

    Optional<String> result= Stream.<Supplier<String>>of(this::method1, this::method2, this::method3)
.map(Supplier::get)
.filter(Objects::nonNull)
.findFirst();
System.out.println(result.isPresent());

上面的代码等同于此(用Intellij Idea生成)

    Optional<String> result = Optional.empty();
for (Supplier<String> stringSupplier : Arrays.<Supplier<String>>asList(this::method1, this::method2, this::method3)) {
String s = stringSupplier.get();
if (s != null) {
result = Optional.of(s);
break;
}
}

关于java - 在每次方法调用后检查对象是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47033275/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com