Stream Collector API

Teeing, a hidden gem in the Java API

Last week, I described a use-case for a custom Stream Collector. I received a intriguing comment on Twitter: Interesting article. For completness' sake this specific problem could also be solved using the standard teeing collector— Miguel Martins (@Miguucm) May 3, 2021 Hats off to you, Miguel! Your comment revealed a method I didn’t know! So I decided to investigate what the teeing() method is about. Returns a Collector that is a composite of two downstream collectors.

Stream Collector API

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: Product.java public class Product { private final Long id; (1) priva

Functional Programming API Optional Stream

Optional.stream()

This week, I learned about a nifty 'new' feature of Optional that I want to share in this post. It’s available since Java 9, so its novelty is relative. Let’s start with the following sequence to compute the total price of an order: public BigDecimal getOrderPrice(Long orderId) { List<OrderLine> lines = orderRepository.findByOrderId(orderId); BigDecimal price = BigDecimal.ZERO; (1) for (OrderLine line : lines) { price = price.add(line.getPrice());