Java Stream flatMapToDouble()与实例
Stream flatMapToDouble(Function mapper) 返回一个DoubleStream,它由将此流的每个元素替换为通过对每个元素应用所提供的映射函数而产生的映射流的内容的结果组成。流 flatMapToDouble(Function mapper) 是一个 中间操作。 这些操作始终是懒惰的。中间操作在一个流实例上被调用,在它们完成处理后,它们给出一个流实例作为输出:
注意: 每个映射的流在其内容被放入该流后被关闭。如果一个映射的流是空的,则使用一个空流。
语法
DoubleStream flatMapToDouble(Function <? super T, ? extends DoubleStream> mapper)
其中,DoubleStream是一串原始的 双值元素的序列,T是流元素的类型。流元素的类型。映射器是一个无状态函数 它被应用于每个元素,并且该函数 返回新的流。
例1: flatMapToDouble()函数的操作是将字符串解析为双数。
// Java code for Stream flatMapToDouble// (Function mapper) to get an DoubleStream// 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.DoubleStream; class GFG { // Driver code public static void main(String[] args) { // Creating a list of Strings List<String> list = Arrays.asList("1.5", "2.7", "3", "4", "5.6"); // Using Stream flatMapToDouble(Function mapper) list.stream().flatMapToDouble(num -> DoubleStream.of(Double.parseDouble(num))) .forEach(System.out::println); }}
输出:
1.52.73.04.05.6
例2: flatMapToDouble()函数的操作是返回带有字符串长度的流。
// Java code for Stream flatMapToDouble// (Function mapper) to get an DoubleStream// 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.DoubleStream; 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 flatMapToDouble(Function mapper) // to get length of all strings present in list list.stream().flatMapToDouble(str -> DoubleStream.of(str.length())) .forEach(System.out::println); }}输出:
5.03.013.03.0
