简体   繁体   中英

Java8: “Translate” old ForEach Method into Lambda/Stream

after hours of hopeless search, I decided to create a question. I really didn't find anything how I can transform this old fashioned way of coding to stream/lambda .

Maybe there is someone, who can explain it to me. Thanks.

public double getSum() {
    double sum = 0;
    for (Product product : productList) {
        sum += product.getPrice();
    }
    return sum;
}

你可以使用以下内容:

double sum = productList.stream().mapToDouble(product -> product.getPrice()).sum();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM