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

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


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:

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

Avoiding an exception is always better.

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