Java Stream flatMapToLong()示例
Stream flatMapToLong(Function mapper) 将给定的mapper函数应用于流的每个元素,并返回一个LongStream。Stream flatMapToLong(Function mapper)是一个 中间操作。 中间操作在一个Stream实例上被调用,在它们完成处理后,它们给出一个Stream实例作为输出:
注意: 每个映射的流在其内容被放入该流后被关闭。如果一个被映射的流是空的,则使用一个空流。
语法
LongStream flatMapToLong(Function <? super T, ? extends LongStream> mapper)
其中,LongStream是一串原始的 长值元素的序列,T是流元素的类型。流元素的类型。映射器是一个无状态函数
它被应用于每个元素,并且该函数 返回新的流。
例1: flatMapToLong()的操作是将字符串解析为长字符串。
// Java code for Stream flatMapToLong
// (Function mapper) to get an LongStream
// 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 a list of Strings
List<String> list = Arrays.asList("1", "2", "3",
"4", "5");
// Using Stream flatMapToLong(Function mapper)
list.stream().flatMapToLong(num ->
LongStream.of(Long.parseLong(num))).
forEach(System.out::println);
}
}
输出:
1
2
3
4
5
例2: flatMapToLong()的操作是用字符串的长度来映射字符串。
// Java code for Stream flatMapToLong
// (Function mapper) to get an LongStream
// 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 a List of Strings
List<String> list = Arrays.asList("Geeks", "GFG",
"GeeksforGeeks", "gfg");
// Using Stream flatMapToLong(Function mapper)
// to get length of all strings present in list
list.stream().flatMapToLong(str ->
LongStream.of(str.length())).
forEach(System.out::println);
}
}
输出:
5
3
13
3
例3: flatMapToLong()函数有返回流的操作。
// Java code for Stream mapToLong
// (ToLongFunction mapper) to get a
// LongStream by applying the given function
// to the elements of this stream.
import java.util.*;
import java.util.stream.LongStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating a list of Strings
List<String> list = Arrays.asList("5.36","27.9",
"3","4.2","5");
// Using Stream mapToLong(ToLongFunction mapper)
// and displaying the corresponding LongStream
list.stream().flatMapToLong(n
-> LongStream.of(Long.parseLong(n)) )
.forEach(System.out::println);
}
}
输出:
Exception in thread "main" java.lang.NumberFormatException: For input string: "5.36"
注意: Java NumberFormatException 通常发生在你试图将一个字符串转换为一个数字值的时候,比如int、float、double、long等等。