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.
import java.util.*;
class GFG {
public static void main(String[] args)
{
List<String> list = Arrays.asList( "3" , "6" , "8" ,
"14" , "15" );
list.stream().mapToInt(num -> Integer.parseInt(num))
.filter(num -> num % 3 == 0 )
.forEach(System.out::println);
}
}
|
Output :
3
6
15
Example 2 : mapToInt() to return IntStream after performing operation of mapping string with its length.
import java.util.*;
class GFG {
public static void main(String[] args)
{
List<String> list = Arrays.asList( "Geeks" , "for" , "gfg" ,
"GeeksforGeeks" , "GeeksQuiz" );
list.stream().mapToInt(str -> str.length()).forEach(System.out::println);
}
}
|
Output :
5
3
3
13
9
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
06 Dec, 2018
Like Article
Save Article