Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Sum of list with stream filter in Java

  • Difficulty Level : Medium
  • Last Updated : 15 May, 2021

We generally iterate through the list when adding integers in a range, but java.util.stream.Stream has a sum() method that when used with filter() gives the required result easily.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

Java




// Simple method (without filter) to find sum of a list
import java.util.*;
 
class Addition {
    public static void main(String[] args)
    {
        // create a list of integers
        List<Integer> list = new ArrayList<Integer>();
 
        // add elements to the list
        list.add(1);
        list.add(5);
        list.add(6);
        list.add(7);
        list.add(8);
        list.add(9);
        list.add(10);
 
        System.out.println(sum(list));
    }
 
    public static int sum(List<Integer> list)
    {
        // iterator for accessing the elements
        Iterator<Integer> it = list.iterator();
 
        int res = 0;
        while (it.hasNext()) {
            int num = it.next();
 
            // adding the elements greater than 5
            if (num > 5) {
                res += num;
            }
        }
 
        return res;
    }
}
Output: 
40

 

The above task can be easily performed using sum() method with filter() method 
 

Java




// Using stream filter to find sum of a list
import java.util.*;
 
class Addition {
    public static void main(String[] args)
    {
        // create a list of integers
        List<Integer> list = new ArrayList<Integer>();
 
        // add elements to the list
        list.add(1);
        list.add(5);
        list.add(6);
        list.add(7);
        list.add(8);
        list.add(9);
        list.add(10);
 
        System.out.println(sum(list));
    }
 
    public static int sum(List<Integer> list)
    {
        // create a stream of integers
        // filter the stream
        // add the integers
        return list.stream()
            .filter(i -> i > 5)
            .mapToInt(i -> i)
            .sum();
    }
}
Output: 
40

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!