gpt4 book ai didi

java - 检查多个变量的 not null 的更短方法

转载 作者:行者123 更新时间:2023-12-01 10:45:32 27 4
gpt4 key购买 nike

我有三个 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;

最佳答案

您可以使用 Stream并这样做:

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

关于java - 检查多个变量的 not null 的更短方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62654530/

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