Best way to convert Integer (maybe null) to int in Java?

An Integermaybe null. I convert Integerto intusing:

Integer integer = null;
int i;

try {
    i = integer.intValue();
}
catch (NullPointerException e) {
    i = -1;
} 

Is there a better way?

+6
source share
4 answers

Avoiding exclusion is always better.

int i = integer != null ? integer.intValue() : -1;
+10
source

If you already have guavaon your class path, I like the answer provided by michaelgulak .

Integer integer = null;
int i = MoreObjects.firstNonNull(integer, -1);
+2
source

Java8 :

Optional.ofNullable(integer).orElse(-1)
0

Source: https://habr.com/ru/post/1612727/


All Articles