Java Streams Interview Trap: map() vs mapToInt() vs mapToDouble() Explained
If youβre working with a Stream<T> (objects), you must convert it to a primitive stream (IntStream, DoubleStream, etc.) before calling average(). π§ Interview-Level Understanding β Rule of Thumbβ¦
If youβre working with a Stream<T> (objects), you must convert it to a primitive stream (IntStream, DoubleStream, etc.) before calling average().
π§ Interview-Level Understanding
β Rule of Thumb
- Object Stream (
Stream<Employee>) β β noaverage() - Primitive Stream (
IntStream,DoubleStream) β β hasaverage()
π So conversion is required when your stream contains objects
π Case-Based Explanation
β Case 1: Object Stream (Your Example)
employees.stream() // Stream<Employee>
.mapToDouble(e -> e.getSalary()) // DoubleStream β
.average();
β Required β because Employee is an object
β Case 2: Already a Primitive Stream
IntStream.of(10, 20, 30)
.average(); // β No conversion needed
β Not required β already IntStream
β Case 3: Using map() instead of mapToX()
employees.stream()
.map(e -> e.getSalary()) // Stream<Double> β
.average(); // β Compile error
π map() keeps it as object stream, not primitive
π₯ Important Interview Insight
Why Java Forces This?
- Performance Optimization
- Primitive streams avoid boxing/unboxing
- Faster operations
- Specialized Methods
average(),sum(),min(),max()exist only in:IntStreamLongStreamDoubleStream
β‘ Quick Cheat Sheet
| Situation | Need mapToX()? |
|---|---|
Stream<Employee> | β Yes |
Stream<Integer> | β Yes |
IntStream | β No |
DoubleStream | β No |
π Final Takeaway (Interview Ready)
βWhenever Iβm working with a Stream of objects and need numeric aggregation like average, I must convert it into a primitive stream using
mapToInt,mapToDouble, ormapToLong. Otherwise,average()wonβt be available.β