A better way to convert Integer (may be null) to int in Java?
24,137
Solution 1
Avoiding an exception is always better.
int i = integer != null ? integer.intValue() : -1;
Solution 2
With Java8 the following works, too:
Optional.ofNullable(integer).orElse(-1)
Solution 3
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 4
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
Related videos on Youtube
Author by
SparkAndShine
For more about me, please refer to, Blog: sparkandshine.net GitHub: https://github.com/sparkandshine WeChat: SparkAndShine
Updated on January 19, 2020Comments
-
SparkAndShine over 4 years
An
Integer
can benull
. I convert anInteger
to anint
by:Integer integer = null; int i; try { i = integer.intValue(); } catch (NullPointerException e) { i = -1; }
Is there a better way?
-
S. Pauk over 8 yearsyou shouldn't use assert in this case cause null is a valid execution path and could indeed happen in production
-
-
Kayaman over 8 yearsDarn you and your fast fingers. I was going for the autoboxing way of
int i = integer == null ? 0 : integer;
. -
S. Pauk over 8 yearsavoiding C legacy notation could also be considered to be a better way by some ppl
-
Eran over 8 years@kocko My original answer (before your edit) without
.intValue()
works fine (Java handles the auto-unboxing). Do you think callingintValue
explicitly is more efficient? -
Konstantin Yovkov over 8 years@Eran, by calling
.intValue()
you avoid the un-boxing and get the primitive value directly. -
khelwood over 8 years@kocko
.intValue()
isn't avoiding unboxing; it is explicitly unboxing -
Konstantin Yovkov over 8 years@khelwood, I don't agree. If you see the source of
Integer#intValue()
you can see that the method returns the nestedprivate final int value;
. So, by assigninginteger.intValue()
to anint
doesn't trigger any boxing/unboxing features of the compiler. However, havingint i = integer;
will actually force the compiler to do unboxing fromInteger
toint
. That's why I find the explicit call to.intValue()
a bit more efficient (even there's not much performance difference) and readable. -
Snekse about 8 yearsHow does NumberUtils or Guava not already have a method for this? They have defaultValue(primary, fallback) for so many things, but not this.
-
Kong over 3 yearsThis is the correct answer for modern Java as it can be done in one assignment. The ternary expression can't.