Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions java-numbers-4/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -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>
Expand Down
Original file line number Diff line number Diff line change
@@ -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();
}

}
Original file line number Diff line number Diff line change
@@ -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));
}

}