BAEL-5418 - Convert long to int type in Java (#8) (#11895)

This commit is contained in:
alemoles 2022-03-07 01:34:14 -05:00 committed by GitHub
parent b88561186e
commit 3fbad0691d
3 changed files with 72 additions and 0 deletions

View File

@ -25,6 +25,11 @@
<version>${commons-lang3.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,44 @@
package com.baeldung.convertLongToInt;
import java.math.BigDecimal;
import java.util.Optional;
import java.util.function.Function;
import com.google.common.primitives.Ints;
public class ConvertLongToInt {
static Function<Long, Integer> convert = val -> Optional.ofNullable(val)
.map(Long::intValue)
.orElse(null);
public static int longToIntCast(long number) {
return (int) number;
}
public static int longToIntJavaWithMath(long number) {
return Math.toIntExact(number);
}
public static int longToIntJavaWithLambda(long number) {
return convert.apply(number);
}
public static int longToIntBoxingValues(long number) {
return Long.valueOf(number)
.intValue();
}
public static int longToIntGuava(long number) {
return Ints.checkedCast(number);
}
public static int longToIntGuavaSaturated(long number) {
return Ints.saturatedCast(number);
}
public static int longToIntWithBigDecimal(long number) {
return new BigDecimal(number).intValueExact();
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.convertLongToInt;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class ConvertLongToIntUnitTest {
@Test
void longToInt() {
long number = 186762L;
int expected = 186762;
assertEquals(expected, ConvertLongToInt.longToIntCast(number));
assertEquals(expected, ConvertLongToInt.longToIntJavaWithMath(number));
assertEquals(expected, ConvertLongToInt.longToIntJavaWithLambda(number));
assertEquals(expected, ConvertLongToInt.longToIntBoxingValues(number));
assertEquals(expected, ConvertLongToInt.longToIntGuava(number));
assertEquals(expected, ConvertLongToInt.longToIntGuavaSaturated(number));
assertEquals(expected, ConvertLongToInt.longToIntWithBigDecimal(number));
}
}