Calculate Sum of List elements using Java Streams


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


Top Hashtags:

Advertisements

Advertisements




Advertisements