LongStream flatMap() method in Java


The flatMap() method in LongStream 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 −

LongStream flatMap(LongFunction<? extends LongStream> mapper)

Here, LongFunction represents a function that accepts a long-valued argument and produces a result.

The parameter wrapper is a stateless function to apply to each element which produces a LongStream of new values.

To use the LongStream class in Java, import the following package −

import java.util.stream.LongStream;

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

Example

 Live Demo

import java.util.*;
import java.util.stream.LongStream;

public class Demo {
   public static void main(String[] args) {
      LongStream longStream1 = LongStream.of(40L, 60L, 90L, 150L, 200L, 300L);
      LongStream longStream2 = longStream1.flatMap(a -> LongStream.of(a + a));
      System.out.println("Updated Stream...");
      longStream2.forEach(System.out::println);
   }
}

Output

Updated Stream...
80
120
180
300
400
600

Updated on: 30-Jul-2019

43 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements