Last Updated : 06 Dec, 2018
LongStream flatMap(LongFunction mapper)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 functionto each element. This 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.
Note :Each mapped stream is closed after its contents have been placed into this stream. If a mapped stream is null, an empty stream is used, instead.
Syntax :LongStream flatMap(LongFunction<? extends LongStream> mapper)Parameters :
LongStream flatMap(LongFunction mapper) returns a stream by a mapped stream using mapping function.
Example 1 :Using LongStream flatMap() to get the cube of elements of LongStream.
Java
// Java code for LongStream flatMap
// (LongFunction mapper) to get a stream
// consisting of the results of replacing
// each element of this stream with the
// contents of a mapped stream
import java.util.*;
import java.util.stream.LongStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating an LongStream
LongStream stream1 = LongStream.of(4L, 5L, 6L, 7L);
// Using LongStream flatMap()
LongStream stream2 = stream1.flatMap(num
-> LongStream.of(num * num * num));
// Displaying the resulting LongStream
stream2.forEach(System.out::println);
}
}
Output :
64 125 216 343Example 2 :
Using LongStream flatMap() to get the count of set bits in binary representation of elements of LongStream.
Java
// Java code for LongStream flatMap
// (LongFunction mapper) to get a stream
// consisting of the results of replacing
// each element of this stream with the
// contents of a mapped stream
import java.util.*;
import java.util.stream.LongStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating an LongStream
LongStream stream1 = LongStream.of(49L, 64L, 81L, 100L);
// Using LongStream flatMap()
LongStream stream2 = stream1.flatMap(num
-> LongStream.of(Long.bitCount(num)));
// Displaying the resulting LongStream
stream2.forEach(System.out::println);
}
}
Output :
3 1 3 3
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4