IntStream flatMap() method in Java


The flatMap() method of the IntStream class returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.

The syntax is as follows

IntStream flatMap(IntFunction<? extends IntStream> mapper)

Here, mapper is a stateless function to apply to each element.

Create an IntStream with elements

IntStream intStream1 = IntStream.of(20, 40, 60, 80, 100, 120, 140);

Now, use the flatMap() function to set a condition that would be replace each element of this stream

IntStream intStream2 = intStream1.flatMap(val -> IntStream.of(val + val));

The following is an example to implement IntStream flatMap() method in Java

Example

 Live Demo

import java.util.*;
import java.util.stream.IntStream;
public class Demo {
   public static void main(String[] args) {
      IntStream intStream1 = IntStream.of(20, 40, 60, 80, 100, 120, 140);
      IntStream intStream2 = intStream1.flatMap(val -> IntStream.of(val + val));
      intStream2.forEach(System.out::println);
   }
}

Output

40
80
120
160
200
240
280z

Updated on: 30-Jul-2019

535 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements