Java中的IntStream flatMap(IntFunction mapper)

IntStream flatMap(IntFunction mapper) 返回一个流,该流包含将该流的每个元素替换为通过应用提供的 映射函数 每一个元素。这是一个 中间操作 .这些操作总是懒惰的。在流实例上调用中间操作,完成处理后,它们将流实例作为输出。

null

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

语法:

IntStream flatMap(IntFunction<? extends IntStream> mapper)

参数:

  1. IntStream: 一个原始的int值元素序列。
  2. IntFunction: 一种接受int值参数并产生结果的函数。
  3. 制图员: 应用于每个元素的无状态函数,该函数返回新流。

返回值: IntStream flatMap(IntFunction mapper)使用映射函数按映射流返回流。

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

// Java code for IntStream flatMap
// (IntFunction 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.IntStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating an IntStream
IntStream stream1 = IntStream.of( 4 , 5 , 6 , 7 );
// Using IntStream flatMap()
IntStream stream2 = stream1.flatMap(num
-> IntStream.of(num * num * num));
// Displaying the resulting IntStream
stream2.forEach(System.out::println);
}
}


输出:

64
125
216
343

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

// Java code for IntStream flatMap
// (IntFunction 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.IntStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating an IntStream
IntStream stream1 = IntStream.of( 49 , 64 , 81 , 100 );
// Using IntStream flatMap()
IntStream stream2 = stream1.flatMap(num
-> IntStream.of(Integer.bitCount(num)));
// Displaying the resulting IntStream
stream2.forEach(System.out::println);
}
}


输出:

3
1
3
3
© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享