Video in progress
What is Collectors.teeing() and what problem does it solve?
teeing (Java 12+) feeds the stream to two collectors at once and combines their results with a function you provide. That way you can compute, say, both the count and the sum in a single pass.
📖 Answer
Say you need the cheapest and the most expensive product from one list. Normally you'd open the stream twice. With teeing, in one pass:
record PriceRange(Product cheapest, Product priciest) {}
PriceRange range = products.stream()
.collect(Collectors.teeing(
Collectors.minBy(Comparator.comparingLong(Product::price)),
Collectors.maxBy(Comparator.comparingLong(Product::price)),
(min, max) -> new PriceRange(min.orElse(null), max.orElse(null))));
Another example: the ratio of failed to total payments:
double failRate = payments.stream()
.collect(Collectors.teeing(
Collectors.counting(),
Collectors.filtering(Payment::failed, Collectors.counting()),
(total, failed) -> total == 0 ? 0.0 : (double) failed / total));
When you need it: the source can't be re-read (a file, a network stream), or the data is large and two passes would be noticeable. On a small list, calling stream() twice is often easier to read, and that's what I choose.
If you need all the numeric statistics, summaryStatistics() or Collectors.summarizingLong is a ready-made solution.
Sign up to mark studied questions and save your progress.