如何将 foreach 表达式重做到流 API 中

问题描述 投票:0回答:1

所以,我有功能:

public static int getMultiSum(List<Test> testList){
    int sum = 0;
    for(Test test : testList){
        sum += test.length * test.width;
    }
    return sum;
}

那么,我如何使用流API来实现这个功能呢?

java java-stream
1个回答
0
投票

您可以使用

mapToInt
Test
流转换为
IntStream
,然后使用归约方法
sum

    public static int getMultiSum(List<Test> testList){
        return testList.stream().mapToInt(t -> t.length * t.width).sum();
    }
© www.soinside.com 2019 - 2024. All rights reserved.