Calculate Sum of List elements using Java Stream


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

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap