🔸 TLDR
▪️ Need two aggregations? teeing() does it in one collect with a clean immutable merge.
🔸 THE PROBLEM
Ever needed two aggregations (ex: count + sum) on the same stream?
The “classic” approach often streams the data twice — simple, but not always ideal.
🔸 CODE: OLD VS MODERN
🔸 SEE A PROBLEM WITH THIS CODE? LET US KNOW 👀
Hint: there’s a subtle one depending on what items is… 😉
🔸 WHY THE MODERN WAY WINS
▪️ ⚡ Single pass: stream once, aggregate twice
▪️ 🧩 Composable: mix any 2 collectors (min/max, summary stats, grouping, etc.)
▪️ 🔒 Immutable result: merge straight into a record / value object
🔸 HOW IT WORKS (IN 1 SENTENCE)
Collectors.teeing() routes each element to two downstream collectors, then merges both results using your merger function (Stats::new here).
🔸 TAKEAWAYS
▪️ Prefer teeing() when you want two results from one stream without mutable accumulators
▪️ Great fit for Stats/DTO/record building
▪️ Still keep readability in mind: for tiny lists, two passes can be totally fine ✅
#Java #Java12 #Streams #Collectors #FunctionalProgramming #CleanCode
#Performance #BackendDevelopment #JVM
https://javaevolved.github.io/collections/collectors-teeing.html
Go further with Java certification:
Java👇
https://www.udemy.com/course/ocp-oracle-certified-professional-java-developer-prep/?referralCode=54114F9AD41F127CB99A
Spring👇
https://www.udemy.com/course/spring-professional-certification-6-full-tests-2v0-7222-a/?referralCode=04B6ED315B27753236AC
SpringBook👇
https://bit.ly/springtify
JavaBook👇
https://bit.ly/jroadmap