How to Convert a List<Long> to List<Integer> in Java (or vice versa!)
Let’s convert between List<Long>
and List<Integer>
in Java.
Suppose 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.
Check out multiple ways to convert a single
long
value to anint
.
1. Using Java 8 streams
We can convert a List<Long>
to a List<Integer>
using map(Long::intValue)
in a stream.
ints = longs.stream()
.map(Long::intValue)
.collec‌t(Collectors.toList(‌​))
And of course, we can convert a List<Integer>
to a List<Long>
using map(Integer::longValue)
.
longs = ints.stream()
.map(Integer::longValue)
.collec‌t(Collectors.toList(‌​))
2. Using a for
loop
We can also use a traditional for
loop to convert between the two types.
We’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());
}