In order to calculate the sum of all elements using Java Streams, we need to make use of the reduce function.
Example:package org.code2care;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
int sum = list.stream().reduce(0,Integer::sum);
System.out.println("Sum="+sum);
}
}
Output:
Sum=100
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!