Stream.mapToInt()
Turns a stream of objects into a stream of `int` numbers.
Available since: Java 8
Syntax
IntStream mapToInt(ToIntFunction<? super T> mapper)Parameters
| Parameter | Type | Description |
|---|---|---|
| mapper | ToIntFunction<? super T> | A function that turns an element into an `int`. |
Return value
IntStreamA stream of primitive numbers.
Examples
The total length of strings:
void main() {
int total = Stream.of("one", "three", "five").mapToInt(String::length).sum();
IO.println(total);
}Output:
12An average price with mapToDouble():
record Product(String name, double price) {}
void main() {
var products = List.of(new Product("a", 10.0), new Product("b", 25.0));
IO.println(products.stream().mapToDouble(Product::price).average().orElse(0));
}Output:
17.5Notes
It gives access to sum(), average() and max() without a comparator and without boxing numbers into Integer. Counterparts: mapToLong(), mapToDouble(). The way back is boxed() or mapToObj().
See also
- IntStream.sum() — Adds up all numbers of a stream.
- IntStream.average() — Computes the arithmetic mean of the numbers in a stream.
- Stream.map() — Transforms every element of a stream.
Related recipes
In the tutorial
- Stream operations — The main Stream API operations — filter, map, sorted, distinct, limit, skip, count, reduce, anyMatch, findFirst and numeric streams.