4

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;
}
Stuart Marks
  • 127,867
  • 37
  • 205
  • 259
Stackman
  • 51
  • 2
  • 4
    As an aside, it's better not to use double for float to represent currency. See http://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency – dnault Jul 12 '15 at 21:56

1 Answers1

3

you can use the following:

double sum = productList.stream().mapToDouble(product -> product.getPrice()).sum();
Kachna
  • 2,921
  • 2
  • 20
  • 34
  • 2
    Alternatively, use a method reference instead of a lambda expression: mapToDouble(Product::getPrice) – dnault Jul 12 '15 at 21:55
  • 1
    Note that you may get slightly different result compared to OP code as stream version implements Kahan summation which is resistant against error accumulation. – Tagir Valeev Jul 13 '15 at 01:44
  • @Tagir Valeev: with `double`s, you can always get differences, even with the same code. – Holger Jul 13 '15 at 12:25