'A better way to convert Integer (may be null) to int in Java?
An Integer can be null. I convert an Integer to an int by:
Integer integer = null;
int i;
try {
i = integer.intValue();
}
catch (NullPointerException e) {
i = -1;
}
Is there a better way?
Solution 1:[1]
With Java8 the following works, too:
Optional.ofNullable(integer).orElse(-1)
Solution 2:[2]
If you already have guava in your classpath, then I like the answer provided by michaelgulak.
Integer integer = null;
int i = MoreObjects.firstNonNull(integer, -1);
Solution 3:[3]
Apache Commons Lang 3
ObjectUtils.firstNonNull(T...)
Java 8 Stream
Stream.of(T...).filter(Objects::nonNull).findFirst().orElse(null)
Taken From: https://stackoverflow.com/a/18741740/6620565
Solution 4:[4]
Java 9 introduce Objects.requireNonNullElse, alternative solution in Java Vanilla (without external library):
Integer integerValue = null;
int intValue = Objects.requireNonNullElse(integerValue, 0);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jens.Huehn_at_SlideFab.com |
| Solution 2 | Community |
| Solution 3 | Luis Andrés Juárez Sandoval |
| Solution 4 | jpep1 |
