1

Java 8 here. I have the following POJO:

@Getter
@Setter
public class Orderline {
    private Integer qty;
    private BigDecimal price;
    private String productName; 
}

I'm looking for a Stream-y way of iterating through a List<Orderlines> and coming up with a subtotal based on their individual quantities and prices. The "old" (pre-Stream) way of doing this would look like:

List<Orderline> orderlines = order.getOrderlines();
double sub = 0.0;
for (Orderline ol : orderlines) {
    sub += ol.getQty() * ol.getPrice();
}

BigDecimal subtotal = BigDecimal.valueOf(sub);

My best attempt at using Streams to accomplish this is:

BigDecimal subtotal = order.getOrderlines().stream()
    .map(Orderline::getPrice)
    .reduce(BigDecimal.ZERO, BigDecimal::add);

However this doesn't take their quantities into consideration. Any ideas how I can accomplish this?

1
  • Can you add an amount() method to the POJO which calculates this value and then use .reduce on that? Commented Sep 11, 2019 at 9:02

1 Answer 1

2

You could use

map(x->x.getPrice().multiply(BigDecimal.valueOf(x.getQty())))

in your second line.

Sign up to request clarification or add additional context in comments.

8 Comments

Thanks @g_bor (+1) but this adds a compiler error: "Operator '*' cannot be applied to 'java.lang.Integer', 'java.math.BigDecimal"
@hotmeatballsoup Then simply replace x.getPrice() * x.getQty() with x.getQty.multiply(BigInteger.valueOf(x.getPrice())).
This is an independent error. It says you can't simply * an Integer and a Bigdecimal. This should cause an error in the old approach also.
@g_bor You could, however, edit your post so this problem is fixed.
Thanks for taking care. I believe it is correct now.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.