2023-12-26 05:00:04

将Long转换为Integer

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


当前回答

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

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

其他回答

长期访客=1000;

int convVisitors =(int)访问者;

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

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

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

如果你使用的是Java 8,请按照下面的步骤操作

    import static java.lang.Math.toIntExact;

    public class DateFormatSampleCode {
        public static void main(String[] args) {
            long longValue = 1223321L;
            int longTointValue = toIntExact(longValue);
            System.out.println(longTointValue);

        }
}
Integer i = theLong != null ? theLong.intValue() : null;

或者如果你不需要担心null:

// auto-unboxing does not go from Long to int directly, so
Integer i = (int) (long) theLong;

在这两种情况下,您都可能遇到溢出(因为Long类型可以比Integer类型存储更大的范围)。

Java 8有一个helper方法来检查溢出(在这种情况下你会得到一个异常):

Integer i = theLong == null ? null : Math.toIntExact(theLong);

最好的简单方法是:

public static int safeLongToInt( long longNumber ) 
    {
        if ( longNumber < Integer.MIN_VALUE || longNumber > Integer.MAX_VALUE ) 
        {
            throw new IllegalArgumentException( longNumber + " cannot be cast to int without changing its value." );
        }
        return (int) longNumber;
    }