Let us convert between List<Long> and List<Integer> in Java.
If we’re working with the following lists:
List<Integer> ints;
List<Long> longs;
We’ll be using Long::intValue and Integer::longValue to convert between the two types.
1. Using Java 8 streams
You can convert a List<Long> to a List<Integer> using map(Long::intValue) in a stream.
ints = longs.stream()
.map(Long::intValue)
.collect(Collectors.toList())
And of course, you can convert a List<Integer> to a List<Long> using map(Integer::longValue).
longs = ints.stream()
.map(Integer::longValue)
.collect(Collectors.toList())
2. Using a for loop
You can also use a traditional for loop to convert between the two types.
You’ll use the same intValue() method to convert from long to int.
for (Long num: longs) {
ints.add(num.intValue());
}
Then, we’ll use longValue() to convert from int to long.
for (Integer num: ints) {
longs.add(num.longValue());
}

Leave a Reply