Java Stream mapToInt Example

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

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

import java.util.stream.Stream; 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); } } 

Output:

Sum of all numbers: 15 

Explanation:

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.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare