DEV Community

Discussion on: Introduction to Java Stream API

Collapse
 
jamoyjamie profile image
Jamie Read

Interesting article, I need to get better at these in Java!

I'm intrigued as to the purpose of the mapToInt in the sum example here:

System.out.println(numbers.stream().mapToInt(Integer::intValue).sum());

Why do you need that? Is numbers not already list of ints?

Collapse
 
lschultebraucks profile image
Lasse Schultebraucks • Edited

Hey Jamie,

I am glad you liked it!

numbers is an array of Integer's. Integer is a class in Java which simply boxs the primitive int type. Therefore I have to call intValue to get access on the actual value of the primitive type.

If you have an int array you can do this:

int[] numbers = {1, 2, 3, 4, 5};

System.out.println(Arrays.stream(numbers).sum());