首页 > 解决方案 > 检查多个变量是否为空的更短方法

问题描述

我有三个Integer变量,不允许我更改为原始变量,int我需要检查其中至少一个的值是否大于 0。下面是否有更短/更简洁的方法来重写我的代码:

Integer foo = // null or some value
Integer bar = // null or some value
Integer baz = // null or some value

boolean atLeastOnePositive = (foo != null && foo > 0) || (bar != null && bar > 0) || (baz != null && baz > 0)

return atLeastOnePositive;

标签: java

解决方案


您可以使用Stream并这样做:

boolean atLeastOnePositive = Stream.of(foo, bar, baz)
  .anyMatch(value -> value != null && value > 0);


推荐阅读