2023-12-26 05:00:04

将Long转换为Integer

如何将一个长值转换为一个整数值在Java?


当前回答

试试这个:

Int i = Long. valueof (L)// L:长值

其他回答

你需要对它进行类型转换。

long i = 100L;
int k = (int) i;

请记住,long类型的范围比int型更大,因此可能会丢失数据。

如果您谈论的是盒装类型,那么请阅读文档。

对于非空值:

Integer intValue = myLong.intValue();

在Java 8中,你可以使用Math.toIntExact。如果你想处理空值,使用:

Integer intVal = longVal == null ? null : Math.toIntExact(longVal);

这个方法的好处是,如果实参(long)溢出int型,它会抛出一个arithmeexception。

试试这个:

Int i = Long. valueof (L)// L:长值

除了@Thilo接受的答案,数学。toIntExact在可选方法链中也很好用,尽管它只接受int作为参数

Long coolLong = null;
Integer coolInt = Optional.ofNullable(coolLong).map(Math::toIntExact).orElse(0); //yields 0