📜  在Java中使用示例流 flatMapToDouble()

📅  最后修改于: 2022-05-13 01:55:16.820000             🧑  作者: Mango

在Java中使用示例流 flatMapToDouble()

Stream flatMapToDouble(函数 mapper)返回一个 DoubleStream,其中包含将此流的每个元素替换为通过将提供的映射函数应用于每个元素而生成的映射流的内容的结果。 Stream flatMapToDouble(函数 mapper) 是一个中间操作。这些操作总是懒惰的。在 Stream 实例上调用中间操作,在它们完成处理后,它们给出一个 Stream 实例作为输出。

注意:每个映射的流在其内容放入此流后关闭。如果映射流为空,则使用空流。
句法 :

DoubleStream flatMapToDouble(Function mapper)

Where, DoubleStream is a sequence of primitive
double-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.

示例 1: flatMapToDouble()函数,具有将字符串解析为 double 的操作。

// 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 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.5
2.7
3.0
4.0
5.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 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.0
3.0
13.0
3.0