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. 

mapToInt_Streams_Signature_Java8_Techndeck

Stream mapToInt in Java 8 with example...!!! Share on X

Example

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:

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:

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts