ZetCode

Java Stream mapToInt

last modified May 25, 2025

This article demonstrates how to use the Java Stream mapToInt method to convert objects to primitive int values in streams.

The mapToInt method is an intermediate operation in Java Streams that transforms a stream of objects into an IntStream, a specialized stream for handling primitive int values. This conversion is particularly beneficial when performing numerical operations, as it eliminates the overhead associated with boxing and unboxing, leading to improved performance.

By using mapToInt, developers can efficiently process numerical data in a functional programming style while leveraging the optimized methods available in IntStream, such as sum, average, max, and min. Since primitive streams avoid the creation of unnecessary wrapper objects, they help reduce memory consumption and enhance execution speed in data-intensive applications.

Basic mapToInt syntax

The mapToInt method converts each element of a stream to a primitive int, producing an IntStream for efficient numeric operations.

IntStream mapToInt(ToIntFunction<? super T> mapper)

The mapper function converts each stream element to an int. The resulting IntStream provides specialized methods for numeric operations like sum, average, min, and max.

Converting strings to lengths

You can use mapToInt to transform a stream of strings into their lengths as primitive int values.

Main.java
void main() {

    Stream.of("apple", "banana", "cherry", "date")
          .mapToInt(String::length)
          .forEach(System.out::println);
}

This example converts a stream of strings to their lengths as primitive ints. The method reference String::length serves as the mapper function.

$ java Main.java
5
6
6
4

Summing values

The mapToInt method allows you to convert and sum values in a single pipeline using IntStream's specialized methods.

Main.java
void main() {

    int total = Stream.of("2", "5", "3", "8")
                     .mapToInt(Integer::parseInt)
                     .sum();
    
    System.out.println("Sum: " + total);
}

This example parses strings to integers and calculates their sum using the IntStream's sum method, which isn't available on regular Streams.

$ java Main.java
Sum: 18

Working with custom objects

You can extract int values from custom objects by mapping each object to one of its integer properties.

Main.java
record Product(String name, int price) {
}

void main() {

    Stream.of(
            new Product("Laptop", 999),
            new Product("Phone", 699),
            new Product("Tablet", 349)
        )
        .mapToInt(Product::price)
        .average()
        .ifPresent(avg -> System.out.printf("Average price: $%.2f%n", avg));
}

This example extracts prices from Product objects and calculates the average using IntStream's average method, which returns an OptionalDouble.

$ java Main.java
Average price: $682.33

Filtering and mapping

You can combine filtering and mapToInt to process only specific elements and then perform numeric operations.

Main.java
void main() {

    Stream.of("1", "two", "3", "four", "5")
          .filter(s -> s.matches("\\d+")) // Only numeric strings
          .mapToInt(Integer::parseInt)
          .max()
          .ifPresent(max -> System.out.println("Max value: " + max));
}

This example filters non-numeric strings, converts the remaining to ints, and finds the maximum value using IntStream's max method.

$ java Main.java
Max value: 5

Handling null values

When mapping to int, it is important to handle potential null values to avoid exceptions during conversion.

Main.java
void main() {

    Stream.of("10", null, "20", "30", null)
          .filter(s -> s != null)
          .mapToInt(Integer::parseInt)
          .forEach(System.out::println);
}

This example shows how to handle null values before converting to int. Attempting to map null directly would result in a NullPointerException.

$ java Main.java
10
20
30

Converting back to object stream

You can convert an IntStream back to a regular Stream of objects using the mapToObj method.

Main.java
void main() {

    IntStream.rangeClosed(1, 5)
             .mapToObj(i -> "Number " + i)
             .forEach(System.out::println);
}

This example shows how to convert an IntStream back to a regular Stream of objects using mapToObj, completing the cycle between primitive and object streams.

$ java Main.java
Number 1
Number 2
Number 3
Number 4
Number 5

Source

Java Stream mapToInt documentation

In this article we have explored the Java Stream mapToInt method. It provides an efficient way to work with primitive int values in streams, offering performance benefits and specialized numeric operations. Understanding when to use primitive streams is important for writing efficient Java code.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all Java tutorials.