Convert Long into Integer

后端 未结 14 2083
伪装坚强ぢ
伪装坚强ぢ 2020-12-07 07:48

How to convert a Long value into an Integer value in Java?

相关标签:
14条回答
  • 2020-12-07 08:06

    The best simple way of doing so is:

    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;
        }
    
    0 讨论(0)
  • 2020-12-07 08:06

    In Java 8 you can use Math.toIntExact. If you want to handle null values, use:

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

    Good thing about this method is that it throws an ArithmeticException if the argument (long) overflows an int.

    0 讨论(0)
  • 2020-12-07 08:08

    You'll need to type cast it.

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

    Bear in mind that a long has a bigger range than an int so you might lose data.

    If you are talking about the boxed types, then read the documentation.

    0 讨论(0)
  • 2020-12-07 08:10

    In java ,there is a rigorous way to convert a long to int

    not only lnog can convert into int,any type of class extends Number can convert to other Number type in general,here I will show you how to convert a long to int,other type vice versa.

    Long l = 1234567L;
    int i = org.springframework.util.NumberUtils.convertNumberToTargetClass(l, Integer.class);
    
    0 讨论(0)
  • 2020-12-07 08:15

    If you care to check for overflows and have Guava handy, there is Ints.checkedCast():

    int theInt = Ints.checkedCast(theLong);
    

    The implementation is dead simple, and throws IllegalArgumentException on overflow:

    public static int checkedCast(long value) {
      int result = (int) value;
      checkArgument(result == value, "Out of range: %s", value);
      return result;
    }
    
    0 讨论(0)
  • 2020-12-07 08:15

    In addition to @Thilo's accepted answer, Math.toIntExact works also great in Optional method chaining, despite it accepts only an int as an argument

    Long coolLong = null;
    Integer coolInt = Optional.ofNullable(coolLong).map(Math::toIntExact).orElse(0); //yields 0
    
    0 讨论(0)
提交回复
热议问题