Sum of list with stream filter in Java

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// Simple method (without filter) to find sum of a list
import java.util.*;
  
class Addition {
    public static void main(String[] args)
    {
        List<Integer> list = new ArrayList<Integer>();
  
        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;
    }
}

chevron_right


Output:

40

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



filter_none

edit
close

play_arrow

link
brightness_4
code

// Using stream filter to find sum of a list
import java.util.*;
  
class Addition {
    public static void main(String[] args)
    {
        List<Integer> list = new ArrayList<Integer>();
  
        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)
    {
        return list.stream().filter(i -> i > 5).mapToInt(i -> i).sum();
    }
}

chevron_right


Output:

40


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.