Teeing, a hidden gem in the Java API

public PriceAndRows getPriceAndRows(Cart cart) {
return cart.getProducts()
.map(CartRow::new) // 1
.collect(Collectors.teeing( // 2
Collectors.reducing( // 3
BigDecimal.ZERO, // 4
CartRow::getRowPrice, // 5
BigDecimal::add), // 6
Collectors.toList(), // 7
PriceAndRows::new // 8
  1. Map each Entry to a CartRow
  2. Call the teeing() method
  3. The first collector computes the price. It’s a simple reducing() call, with:
  4. The starting element
  5. A function to extract a Price from a CartRow
  6. A BinaryOperator to add two prices together
  7. The second collector aggregates the CartRow into a list
  8. Finally, the last parameter creates a new object that aggregates the results from the first and the second collector
  1. Extracts each of the individual components of both Collector, i.e., supplier(), `accumulator(), combiner() and finisher()
  2. Pairs them side-by-side
  3. Creates a single new Collector by passing the pairs

To go further:



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store