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?

hotmeatballsoup
  • 385
  • 6
  • 58
  • 136
  • Can you add an `amount()` method to the POJO which calculates this value and then use `.reduce` on that? – Nicko Sep 11 '19 at 09:02

1 Answers1

2

You could use

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

in your second line.

g_bor
  • 1,077
  • 6
  • 14
  • Thanks @g_bor (+1) but this adds a compiler error: "`Operator '*' cannot be applied to 'java.lang.Integer', 'java.math.BigDecimal`" – hotmeatballsoup Sep 10 '19 at 19:32
  • 2
    @hotmeatballsoup Then simply replace `x.getPrice() * x.getQty()` with `x.getQty.multiply(BigInteger.valueOf(x.getPrice()))`. – MC Emperor Sep 10 '19 at 19:35
  • 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 Sep 10 '19 at 19:35
  • @g_bor You could, however, edit your post so this problem is fixed. – MC Emperor Sep 10 '19 at 19:38
  • Thanks for taking care. I believe it is correct now. – g_bor Sep 10 '19 at 19:43
  • Thanks guys, but `qty` is an `Integer` field and there is no `multiple(...)` method on it. The `price` is the `BigDecimal`. The posted solution still does not work! – hotmeatballsoup Sep 10 '19 at 19:54
  • You are right, and the type was not correct either... Sorry. – g_bor Sep 10 '19 at 20:03
  • This thread answers that part of the question: https://stackoverflow.com/questions/49853552/how-to-convert-integer-to-bigdecimal-in-java – g_bor Sep 10 '19 at 20:05