Sum of list with stream filter in Java

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.
Java
// Simple method (without filter) to find sum of a listimport 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 listimport 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
Â



