In the Stream API, mapToInt() is a specialized intermediate operation used to convert a generic Stream (like Stream<Integer>) into a primitive IntStream.
Here is why and how to use it:
1. Why convert to IntStream?
In your lab code:
List<Integer> numbers = Arrays.asList(10, 2, 30, 5, 4, 20);
numbers.stream().mapToInt(Integer::intValue).average();
A standard Stream<Integer> works with Objects. However, mathematical operations like sum(), average(), or summaryStatistics() are only available on primitive streams like IntStream, LongStream, or DoubleStream.
By using mapToInt(), you "unwrap" the Integer objects into primitive int values, which unlocks these specialized math methods.
2. The Syntax
The method expects a ToIntFunction. This is a functional interface that tells Java how to turn your object into an int.
Common ways to use it:
- With Method References:
Integer::intValue(as seen in your lab). - With Custom Objects:
userStream.mapToInt(User::getAge)(extracts an int property). - With Simple Math:
numbers.stream().mapToInt(n -> n * 2)(transforms the value).
3. What comes after mapToInt()?
Once you have an IntStream, you can perform efficient primitive operations:
.average(): Returns anOptionalDouble..sum(): Returns anint..max()/.min(): Returns anOptionalInt..summaryStatistics(): Returns an object containing count, sum, min, average, and max all at once!
Example: Using summaryStatistics
This is a very cool feature once you've used mapToInt():
IntSummaryStatistics stats = numbers.stream()
.mapToInt(Integer::intValue)
.summaryStatistics();
System.out.println("Max: " + stats.getMax());
System.out.println("Min: " + stats.getMin());
System.out.println("Sum: " + stats.getSum());
System.out.println("Ave: " + stats.getAverage());
Labby's Tip: Using mapToInt is also better for performance when dealing with large datasets because it avoids the overhead of "autoboxing" (converting primitives back and forth into objects).