A better way to convert Integer (may be null) to int in Java?

Apache Commons Lang 3


Java 8 Stream


Taken From: https://stackoverflow.com/a/18741740/6620565

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);

With Java8 the following works, too:


Avoiding an exception is always better.

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