How I can redo foreach expression into stream API

So, I have function:

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

So, how I can use stream API for this function?

>Solution :

You can use mapToInt to convert the Test stream to an IntStream, then use the reduction method sum.

    public static int getMultiSum(List<Test> testList){
        return testList.stream().mapToInt(t -> t.length * t.width).sum();
    }

Leave a Reply