Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a list of long to a iterable of integers using Java 8

Tags:

java

java-8

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?

like image 542
user3369592 Avatar asked Jan 04 '18 22:01

user3369592


2 Answers

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());
like image 96
Ousmane D. Avatar answered Nov 01 '22 17:11

Ousmane D.


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());
like image 33
Peter Lawrey Avatar answered Nov 01 '22 17:11

Peter Lawrey