如何在Java中检查Integer是null还是零?

Myk*_*ych 27 java

是否有更简洁的写作方式

if (myInteger != null && myInteger != 0) { ... }
Run Code Online (Sandbox Code Playgroud)

例如,对于Strings,您可以使用StringUtils.isBlank()

Flo*_*cht 14

使用Java 8:

if (Optional.ofNullable(myInteger).orElse(0) != 0) {
  ...
}
Run Code Online (Sandbox Code Playgroud)

请注意Optional,根据您的使用情况,可以帮助您完全避免if条件...

  • 如果没有 intValue(),这个条件可能会少一些:) `if (Optional.ofNullable(myInteger).orElse(0) != 0) { ....` (2认同)

Yoo*_* N. 7

由于StringUtils问题中提到了类,我假设项目中已经使用了 Apache Commons lib。

然后您可以使用以下内容:

if (0 != ObjectUtils.defaultIfNull(myInteger, 0)) { ... }
Run Code Online (Sandbox Code Playgroud)

或者使用静态导入:

if (0 != defaultIfNull(myInteger, 0)) { ... }
Run Code Online (Sandbox Code Playgroud)


Axe*_*elH 5

我将为此使用三元条件。就像是 :

public static boolean isNullorZero(Integer i){
    return 0 == ( i == null ? 0 : i);
}
Run Code Online (Sandbox Code Playgroud)

我同意这不可读;)

  • 我==空|| i==0 是不是很容易:P (2认同)