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?
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?
With Java8 the following works, too:
Optional.ofNullable(integer).orElse(-1)
Avoiding an exception is always better.
int i = integer != null ? integer.intValue() : -1;
Java 9 introduce Objects.requireNonNullElse, alternative solution in Java Vanilla (without external library):
Integer integerValue = null;
int intValue = Objects.requireNonNullElse(integerValue, 0);
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);
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