I've noticed many functionalities exposed in Stream are apparently duplicated in Collectors, such as Stream.map(Foo::bar)
versus Collectors.mapping(Foo::bar, ...)
, or Stream.count()
versus Collectors.counting()
. What's the difference between these approaches? Is there a performance difference? Are they implemented differently in some way that affects how well they can be parallelized?
Java Stream.map vs Collectors.mapping – Key Differences
javajava-8java-stream
Related Question
- Java 8 – Difference Between map() and flatMap() Methods
- Java – Difference Between StringBuilder and StringBuffer
- Simplest Way to Print a Java Array
- Java – Difference Between SoftReference and WeakReference
- Java – Difference Between JDK and JRE
- Java – Difference Between Instant and LocalDateTime
- Java – Difference Between HashMap, LinkedHashMap, and TreeMap
Best Answer
The collectors that appear to duplicate functionality in
Stream
exist so they can be used as downstream collectors for collector combinators likegroupingBy()
.As a concrete example, suppose you want to compute "count of transactions by seller". You could do:
Without collectors like
counting()
ormapping()
, these kinds of queries would be much more difficult.