Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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

ParameterTypeDescription
mapperToIntFunction<? 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:

12

An 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.5

Notes

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

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.

Thanks for reading!

Donate to the site — we work hard for you.