mapToInt, mapToLong, mapToDouble: Primitive Specializations
You'll learn how to convert object streams to primitive streams for better performance and memory efficiency.
The Problem with Generic Streams
When you use the regular map operation, you always get a Stream<T> of objects. Even when transforming to numbers, you end up with Stream<Integer>, Stream<Long>, or Stream<Double>. This means boxing overhead—every primitive value gets wrapped in an object, consuming extra memory and CPU cycles.
Primitive Stream Specializations
Java provides three specialized mapping operations that convert to primitive streams:
mapToInt()returns anIntStreammapToLong()returns aLongStreammapToDouble()returns aDoubleStream
These methods eliminate boxing, use less memory, and unlock primitive-specific operations like sum(), average(), and max().
Basic Examples
List<String> words = List.of("cat", "elephant", "ox");
// Regular map: Stream<Integer> with boxing
Stream<Integer> lengths = words.stream()
.map(String::length);
// mapToInt: IntStream without boxing
IntStream lengthsInt = words.stream()
.mapToInt(String::length);
List<Product> products = getProducts();
// Extract prices as DoubleStream
DoubleStream prices = products.stream()
.mapToDouble(Product::getPrice);
// Now you can use primitive operations
double total = prices.sum();
When to Use Them
Use these specializations whenever you're mapping to numeric values and plan to perform arithmetic operations or terminal operations like sum(), average(), min(), or max(). The performance gain is especially noticeable with large datasets.
Key Takeaway: Use mapToInt, mapToLong, and mapToDouble instead of regular map when transforming to numbers—they eliminate boxing overhead and provide specialized numeric operations unavailable on generic streams.