Teeing, a hidden gem in the Java API
I prefer imperative code over collector like APIs for two reasons, both visible in this example:<p>1. The intention of the code is obscured by more layers of abstraction, increasing complexity.<p>2. Small changes to what the code is conceptually doing tend to lead to larger changes to the actual code than with imperative code.<p>For the first point, reading through this post and the previous post linked, the code is doing the following:<p>Taking the entries of a map of product to count.  Turning those entries into a different class, a row of each product and count.  Then it collects this list on one hand.  On the other hand, it sums the total, based on the per product cost and the count of the product in the cart.  Then it combines the row list and the total cost into one object, returning it.<p>Deconstructed, half of this code is just unnecessary complexity.  A map of products to count, and a list of unique product&#x2F;count tuples are theoretically identical.  You can iterate over them, find specific products, etc.  There &#x2F;might&#x2F; be a reason to specifically desire a list;  However why would that code be coupled with code to sum the cost of the cart?<p>All in all, why is the code not just:<p><pre><code>  public BigDecimal sumPrice(Cart cart) {
    BigDecimal sum = BigDecimal.ZERO;
    for (Map.Entry&lt;Product,Integer&gt; entry : cart.getProducts.entrySet()) {
      sum = sum.add(entry.getKey().getPrice().multiply(new BigInteger(entry.getValue())
    }
    return sum;
  }
</code></pre>
For the second point, briefly:  Consider how code would have to change to calculate a deal, such as Buy One Get One Free.  Such code to do this calculation would add another layer to the collector with another function defined somewhere (or hidden in some other existing abstraction, such as OP&#x27;s CartRow::getRowPrice) instead of just visible in the function that calculates a cart subtotal.  If the deal relied upon concepts not limited to one row at a time, eg buy any two flavors of chips for % off, the proposed solution would have to be completely rewritten.