by BehindJava
WAP to find the sum of all the numbers in a list using in Java 8
In this blog, we are going to learn about finding the sum of all the numbers in a list using in Java 8.
Stream java.util.Collection.stream()
Returns a sequential Stream with this collection as its source.
java.util.stream.Stream.mapToInt(ToIntFunction<? super Integer> mapper)
Returns an IntStream consisting of the results of applying the given function to the elements of this stream.
java.util.stream.IntStream.sum()
Returns the sum of elements in this stream. This is a special case of a reduction and is equivalent to:
return reduce(0, Integer::sum);
This is a terminal operation.
Returns:
the sum of elements in this stream
Example:
import java.util.Arrays;
import java.util.List;
public class BehindJava {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(77, 42, 35, 12, 101, 5);
int sum = list.stream().mapToInt(n -> n).sum();
System.out.println("Sum: " + sum);
}
}
Output:
Sum: 272