Converting a long list to an iterable of integers using Java 8

How do I convert a long list 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. 

Can someone tell me how to fix this?

+5
source share
2 answers

You will need Long::intValue , not Long::valueOf , since this function returns the type Long not int .

 Iterable<Integer> result = longList.stream() .map(Long::intValue) .collect(Collectors.toList()); 

or if you want the receiver type to be List<Integer> :

 List<Integer> result = longList.stream() .map(Long::intValue) .collect(Collectors.toList()); 
+11
source

If you are not worried about overflow or underflow, you can use Long::intValue , however, if you want to throw an exception, if that happens, you can do

 Iterable<Integer> result = longList.stream() .map(Math::toIntExact) // throws ArithmeticException on under/overflow .collect(Collectors.toList()); 

If you prefer to โ€œsaturateโ€ a 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()); 
+2
source

Source: https://habr.com/ru/post/1274514/


All Articles