How could I convert a list of long to a list of integers. I wrote :
longList.stream().map(Long::valueOf).collect(Collectors.toList())
//longList is a list of long.
I have an error :
Incompatible types. Required iterable<integer> but collect was inferred to R.
May anyone tell me how to fix this?
You'll need Long::intValue
rather than Long::valueOf
as this function returns a Long
type not int
.
Iterable<Integer> result = longList.stream()
.map(Long::intValue)
.collect(Collectors.toList());
or if you want the receiver type as List<Integer>
:
List<Integer> result = longList.stream()
.map(Long::intValue)
.collect(Collectors.toList());
If you are not concerned about overflow or underflows you can use Long::intValue
however if you want to throw an exception if this occurs you can do
Iterable<Integer> result =
longList.stream()
.map(Math::toIntExact) // throws ArithmeticException on under/overflow
.collect(Collectors.toList());
If you would prefer to "saturate" the value you can do
Iterable<Integer> result =
longList.stream()
.map(i -> (int) Math.min(Integer.MAX_VALUE,
Math.max(Integer.MIN_VALUE, i)))
.collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With