java 在Java中将Integer(可能为null)转换为int的更好方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33277625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 21:28:10  来源:igfitidea点击:

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

javaintegerintconverter

提问by SparkAndShine

An Integercan be null. I convert an Integerto an intby:

一个Integer可以null。我将 an 转换Integer为 an int

Integer integer = null;
int i;

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

Is there a better way?

有没有更好的办法?

回答by Eran

Avoiding an exception is always better.

避免异常总是更好。

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

回答by Jens.Huehn_at_SlideFab.com

With Java8 the following works, too:

使用 Java8 也可以执行以下操作:

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

回答by Snekse

If you already have guavain your classpath, then I like the answer provided by michaelgulak.

如果您guava的类路径中已经有了,那么我喜欢michaelgulak 提供答案

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