📜  Java中带有流过滤器的列表总和

📅  最后修改于: 2022-05-13 01:54:31.889000             🧑  作者: Mango

Java中带有流过滤器的列表总和

当在一个范围内添加整数时,我们通常会遍历列表,但是Java.util.stream.Stream有一个sum()方法,当与filter()一起使用时,它很容易给出所需的结果。

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 list = new ArrayList();
 
        // 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 list)
    {
        // iterator for accessing the elements
        Iterator 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;
    }
}


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 list = new ArrayList();
 
        // 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 list)
    {
        // create a stream of integers
        // filter the stream
        // add the integers
        return list.stream()
            .filter(i -> i > 5)
            .mapToInt(i -> i)
            .sum();
    }
}


输出:
40

使用sum()方法和filter()方法可以轻松执行上述任务

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 list = new ArrayList();
 
        // 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 list)
    {
        // create a stream of integers
        // filter the stream
        // add the integers
        return list.stream()
            .filter(i -> i > 5)
            .mapToInt(i -> i)
            .sum();
    }
}
输出:
40