What is the Stream.mapToInt() method in Java?

Overview

The mapToInt() method of the Stream interface is used to return an IntStream that contains the results of applying the provided implementation of the ToIntFunction() function on the stream’s items.

Syntax


IntStream mapToInt(ToIntFunction<? super T> mapper)

Parameters

  • ToIntFunction<? super T> mapper: This is the mapper function that needs to be applied.

Return value

This method returns a new stream.

Code

import java.util.Arrays;
import java.util.List;
import java.util.function.ToIntFunction;
public class Main{
public static void main(String[] args) {
// define the list of integers
List<Integer> integerList = Arrays.asList(10, 24, 54, 8,232);
// Define the implementation of ToIntFunction interface
ToIntFunction<Integer> multiplyByTwo = e -> e * 2;
// apply the multiplyByTwo using mapToInt function and print each value
integerList.stream().mapToInt(multiplyByTwo).forEach(System.out::println);
}
}
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources