Java 25 (LTS) reference · Stream API
Java Stream mapToInt() Method
Map to an IntStream of primitive ints, which has sum(), average(), min(), max() and summaryStatistics().
Java 25 (LTS) Since Java 8
Syntax
stream.mapToInt(mapper)
Parameters
| Parameter | Description |
|---|---|
mapperToIntFunction<T> |
Function returning an int. |
Return value
An IntStream.
Examples
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
List<String> words = List.of("java", "streams", "api");
System.out.println(words.stream().mapToInt(String::length).sum());
System.out.println(words.stream().mapToInt(String::length).max().getAsInt());
}
}
Output
14 7
Run this on your computer — see “Get Started” for setup.
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
IntSummaryStatistics stats = Stream.of(70, 85, 92).mapToInt(Integer::intValue).summaryStatistics();
System.out.println(stats.getMin() + " " + stats.getMax() + " " + stats.getAverage());
System.out.println(IntStream.rangeClosed(1, 5).sum());
}
}
Output
70 92 82.33333333333333 15
Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| Java Java 8 | Added |
Related
stream.reduce()· Combine all elements into one value with an accumulator function, starting from an identity value.stream.map()· Transform each element with a function and return a stream of the results.- Java Streams · tutorial