Stream flatMapToLong() in Java with examples
Stream flatMapToLong(Function mapper) applies given mapper function to each element of a stream and returns a LongStream. Stream flatMapToLong(Function mapper) is an intermediate operation. 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 flatMapToLong(Function<? super T, ? extends LongStream> mapper)
Where, LongStream is a sequence of primitive
long-valued elements and T is the type
of stream elements. mapper is a stateless function
which is applied to each element and the function
returns the new stream.
Example 1 : flatMapToLong() with operation of parsing string to long.
import java.util.*;
import java.util.stream.LongStream;
class GFG {
public static void main(String[] args)
{
List<String> list = Arrays.asList( "1" , "2" , "3" ,
"4" , "5" );
list.stream().flatMapToLong(num ->
LongStream.of(Long.parseLong(num))).
forEach(System.out::println);
}
}
|
Output :
1
2
3
4
5
Example 2 : flatMapToLong() with operation of mapping string with string length.
import java.util.*;
import java.util.stream.LongStream;
class GFG {
public static void main(String[] args)
{
List<String> list = Arrays.asList( "Geeks" , "GFG" ,
"GeeksforGeeks" , "gfg" );
list.stream().flatMapToLong(str ->
LongStream.of(str.length())).
forEach(System.out::println);
}
}
|
Output :
5
3
13
3
Example 3 : flatMapToLong() function with operation of returning stream.
import java.util.*;
import java.util.stream.LongStream;
class GFG {
public static void main(String[] args)
{
List<String> list = Arrays.asList( "5.36" , "27.9" ,
"3" , "4.2" , "5" );
list.stream().flatMapToLong(n
-> LongStream.of(Long.parseLong(n)) )
.forEach(System.out::println);
}
}
|
Output :
Exception in thread "main" java.lang.NumberFormatException: For input string: "5.36"
Note : A Java NumberFormatException usually occurs when you try to do something like converting a String to a numeric value, like an int, float, double, long etc.
Last Updated :
06 Dec, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...