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());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.