diff --git a/java-numbers-4/pom.xml b/java-numbers-4/pom.xml index 9b2e799840..40fe17cc0d 100644 --- a/java-numbers-4/pom.xml +++ b/java-numbers-4/pom.xml @@ -25,6 +25,11 @@ ${commons-lang3.version} test + + com.google.guava + guava + ${guava.version} + diff --git a/java-numbers-4/src/main/java/com/baeldung/convertLongToInt/ConvertLongToInt.java b/java-numbers-4/src/main/java/com/baeldung/convertLongToInt/ConvertLongToInt.java new file mode 100644 index 0000000000..0638505c2d --- /dev/null +++ b/java-numbers-4/src/main/java/com/baeldung/convertLongToInt/ConvertLongToInt.java @@ -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 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(); + } + +} diff --git a/java-numbers-4/src/test/java/com/baeldung/convertLongToInt/ConvertLongToIntUnitTest.java b/java-numbers-4/src/test/java/com/baeldung/convertLongToInt/ConvertLongToIntUnitTest.java new file mode 100644 index 0000000000..38fa37b664 --- /dev/null +++ b/java-numbers-4/src/test/java/com/baeldung/convertLongToInt/ConvertLongToIntUnitTest.java @@ -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)); + } + +} \ No newline at end of file