In this tutorial, we will see “what is mapToInt() operation as part of streams introduced in Java 8 with example?”
mapToInt() returns an IntStream consisting of the results of applying the given function to the elements of this stream. This is an intermediate operation.
Stream mapToInt in Java 8 with example...!!! Share on X
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | import java.util.Arrays; import java.util.List; import java.util.function.ToIntFunction; public class MapToInt_Stream_Java8_Example { public static void main(String[] args) { System.out.println("mapToInt example - filtering even numbers"); List <String> list = Arrays.asList("5", "14", "23", "98", "76"); //Anonymous Implementation System.out.println("Using Anonymous Impl"); list.stream().mapToInt(new ToIntFunction <String> () { @Override public int applyAsInt(String value) { return Integer.parseInt(value); } }).filter(value -> value % 2 == 0).forEach(value -> System.out.println(value)); //Lambda Implementation System.out.println("Using Lambda Impl"); list.stream().mapToInt(value -> Integer.parseInt(value)).filter(value -> value % 2 == 0).forEach(value -> System.out.println(value)); } } |
Output:
1 2 3 4 5 6 7 8 | Using Anonymous Impl 14 98 76 Using Lambda Impl 14 98 76 |
Stream mapToInt in Java 8 with example...!!! Share on X
Do you like this Post? – then check my other helpful posts:
- Double the even / odd numbers of a specified ArrayList using Streams
- Double the numbers of specified ArrayList using Streams