Java Stream mapToInt Example

1. Introduction

This tutorial explores the mapToInt() method in the Java Stream API. mapToInt() is used to convert objects within a stream into integers. This is particularly useful for transforming streams where you need to perform numerical calculations or aggregate operations on integer values.

Key Points

1. mapToInt() converts each element of a stream to an integer using a provided int-producing function.

2. It returns an IntStream, which is a stream of primitive int values, allowing for operations that are more efficient than those on a Stream<Integer>.

3. This method is commonly used for operations like summing, finding min or max, or averaging, which require integer values.

2. Program Steps

1. Create a Stream of elements.

2. Apply mapToInt() to transform these elements into integers.

3. Perform operations on the resulting IntStream.

3. Code Program


public class StreamMapToIntExample {

    public static void main(String[] args) {
        // Stream of strings representing numerical values
        Stream<String> stringStream = Stream.of("1", "2", "3", "4", "5");

        // Converting string values to integers and calculating their sum
        int sum = stringStream.mapToInt(Integer::parseInt).sum();
        System.out.println("Sum of all numbers: " + sum);


Sum of all numbers: 15


1. Stream.of("1", "2", "3", "4", "5") creates a stream of strings. Each string represents a numerical value.

2. stringStream.mapToInt(Integer::parseInt) converts each string in the stream to an integer using Integer.parseInt. This transforms the stream of strings into an IntStream.

3. .sum() is called on the resulting IntStream to calculate the sum of all the integers. The method efficiently handles the arithmetic operation on the stream of primitive int values.