A real-world example of a Stream Collector

Java Stream’s Collectors methods fit most use-cases. They allow returning either a Collection or a scalar. For the former, you use one of the toXXX() method, for the latter, one of the reducing() one.

Let’s imagine an e-commerce platform that implements a shopping cart. The cart is modeled as the following:

This diagram might translate into the following (abridged) code:

  1. Getters
  2. Only depend on id
  1. Organize products into a map. The key is the Product; the value is the quantity.
  2. Remember to return a read-only copy of the collection to maintain encapsulation.

Once we have defined how we store data in memory, we need to design how to display the cart on-screen. We know that the checkout screen needs to show two different bits of information:

  • The list of rows with the price for each row, i.e., the price per product times the quantity.
  • The overall price of the cart.

Here’s the corresponding code:

  1. CartRow is a value object. We can model it as a Java 16 record.
  1. Collect the list of rows.
  2. Compute the price for each row.
  3. Compute the total price.

One of the main limitations of Java streams is that you can only consume them once. The reason is that streamed objects are not necessarily immutable (though they can be). Hence, executing the same stream twice might not be idempotent.

Therefore, to get both the rows and the price, we need to create two streams from the cart. From one stream, we will get the rows and from the other the price. This is not the way.

We want to collect both rows and the price from a single stream. We need a custom Collector that returns both in one pass as a single object.

  1. Total cart price.
  2. List of cart rows that can display the product’s label, the product’s price, and the row price.

Here’s a summary of the Collector interface. For more details, please check this previous post.

  • supplier(): Supply the base object to start from
  • accumulator(): Describe how to accumulate the current streamed item to the container
  • combiner(): If the stream is parallel, describe how to merge them
  • finisher(): If the mutable container type is not the returned type, describe how to transform the former into the latter
  • characteristics(): Provide meta-data to optimize the stream |

Given this, we can implement the Collector accordingly:

  1. The mutable container is an instance of PriceAndRows.
  2. For each map entry containing the product and the quantity, accumulate both into the PriceAndRows.
  3. Two PriceAndRows can be combined by summing their total price and aggregating their respective rows.
  4. The mutable container can be returned as-is.

Designing the Collector is a bit involved, but using the custom collector is as easy as:

Conclusion

You can solve most use cases with one of the out-of-the-box collectors provided in the Collectors class. However, some require to implement a custom Collector, e.g., when you need to collect more than a single collection or a single scalar.

While it may seem complicated if you never developed one before, it’s not. You only need a bit of practice. I hope this post might help you with it.

You can find the source code of this post on GitHub in Maven format.

To go further

Originally published at A Java Geek on May 2nd, 2021

--

--

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
Nicolas Fränkel

Dev Advocate for Apache APISIX. Former developer and architect. Still teaching, learning and blogging.