如何在Java中执行类似以下JavaScript代码的操作?
var result = getA() || getB() || getC() || 'all of them were undefined!';
我想要做的是继续评估语句或方法,直到它得到一些东西而不是null
.
我希望调用者代码简单有效.
你可以为它创建一个方法.
public staticT coalesce(Supplier ... ts) { return asList(ts) .stream() .map(t -> t.get()) .filter(t -> t != null) .findFirst() .orElse(null); }
代码取自:http://benjiweber.co.uk/blog/2013/12/08/null-coalescing-in-java-8/
编辑正如评论中所述.在下面找到一个小片段如何使用它.使用Stream
API比使用vargs
方法参数更有优势.如果方法返回的值很昂贵而且简单的getter不返回,那么vargs
解决方案将首先评估所有这些方法.
import static java.util.Arrays.asList; import java.util.function.Supplier; ... static class Person { String name; Person(String name) { this.name = name; } public String name() { System.out.println("name() called for = " + name); return name; } } public staticT coalesce(Supplier ... ts) { System.out.println("called coalesce(Supplier ... ts)"); return asList(ts) .stream() .map(t -> t.get()) .filter(t -> t != null) .findFirst() .orElse(null); } public static T coalesce(T... ts) { System.out.println("called coalesce(T... ts)"); for (T t : ts) { if (t != null) { return t; } } return null; } public static void main(String[] args) { Person nobody = new Person(null); Person john = new Person("John"); Person jane = new Person("Jane"); Person eve = new Person("Eve"); System.out.println("result Stream API: " + coalesce(nobody::name, john::name, jane::name, eve::name)); System.out.println(); System.out.println("result vargas : " + coalesce(nobody.name(), john.name(), jane.name(), eve.name())); }
产量
called coalesce(Supplier... ts) name() called for = null name() called for = John result Stream API: John name() called for = null name() called for = John name() called for = Jane name() called for = Eve called coalesce(T... ts) result vargas : John
如输出中所示.在Stream
解决方案中,将在coalesce
方法内部评估返回值的方法.只执行两次,因为第二次调用返回预期non-null
值.在vargs
解决方案中,在coalesce
调用方法之前,将评估返回值的所有方法.