📜  Java中的 LongStream flatMap(LongFunction mapper)

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

Java中的 LongStream flatMap(LongFunction mapper)

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

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

句法 :

LongStream flatMap(LongFunction mapper)

参数 :

  1. LongStream :原始长值元素的序列。
  2. LongFunction :接受长值参数并产生结果的函数。
  3. mapper :应用于每个元素的无状态函数,该函数返回新流。

返回值: LongStream flatMap(LongFunction mapper) 使用映射函数通过映射流返回一个流。

示例 1:使用 LongStream flatMap() 获取 LongStream 元素的立方体。

// 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);
    }
}

输出 :

64
125
216
343

示例 2:使用 LongStream flatMap() 获取 LongStream 元素的二进制表示中的设置位计数。

// 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);
    }
}

输出 :

3
1
3
3