Stream mapToInt() in Java with examples

Stream mapToInt(ToIntFunction mapper) returns an IntStream consisting of the results of applying the given function to the elements of this stream.

Stream mapToInt(ToIntFunction mapper) is an intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, they give a Stream instance as output.

Syntax :



IntStream mapToInt(ToIntFunction<? super T> mapper)

Where, IntStream is a sequence of primitive 
int-valued elements and T is the type 
of stream elements. mapper is a stateless function 
which is applied to each element and the function
returns the new stream.

Example 1 : mapToInt() with operation of printing the stream element if divisible by 3.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code for Stream mapToInt
// (ToIntFunction mapper) to get a
// IntStream by applying the given function
// to the elements of this stream.
import java.util.*;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Creating a list of Strings
        List<String> list = Arrays.asList("3", "6", "8"
                                            "14", "15");
  
        // Using Stream mapToInt(ToIntFunction mapper)
        // and displaying the corresponding IntStream
        list.stream().mapToInt(num -> Integer.parseInt(num))
                     .filter(num -> num % 3 == 0)
                     .forEach(System.out::println);
    }
}

chevron_right


Output :

3
6
15

Example 2 : mapToInt() to return IntStream after performing operation of mapping string with its length.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code for Stream mapToInt
// (ToIntFunction mapper) to get a
// IntStream by applying the given function
// to the elements of this stream.
import java.util.*;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Creating a list of Strings
        List<String> list = Arrays.asList("Geeks", "for", "gfg",
                                          "GeeksforGeeks", "GeeksQuiz");
  
        // Using Stream mapToInt(ToIntFunction mapper)
        // and displaying the corresponding IntStream
        // which contains length of each element in
        // given Stream
        list.stream().mapToInt(str -> str.length()).forEach(System.out::println);
    }
}

chevron_right


Output :

5
3
3
13
9


My Personal Notes arrow_drop_up

In love with a semicolon because sometimes i miss it so badly)

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.