我有这个简单的片段,我希望以更优雅的方式重新设计,可能使用最新的JDK 8功能:
String x = methodCall();
if(x==null) {x=method2();}
if(x==null) {x=method3();}
if(x==null) {x=method4();}
// doing calculation with X
Run Code Online (Sandbox Code Playgroud)
您可以使用Streams:
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());
Run Code Online (Sandbox Code Playgroud)
上面的代码与此相同(使用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;
}
}
Run Code Online (Sandbox Code Playgroud)