Java中的 Stream peek() 方法及示例
在Java中,Stream 为处理数据提供了一种强大的替代方案,在这里我们将讨论一个非常常用的名为peek() 的方法,它是一个消费者操作,它基本上返回一个由该流的元素组成的流,另外还执行提供的操作在每个元素上,因为元素是从结果流中消耗的。这是一个中间操作,因为它创建了一个新流,在遍历该流时,它包含与给定谓词匹配的初始流的元素。
句法:
Stream peek(Consumer super T> action)
这里,Stream 是一个接口,T 是流元素的类型。动作是对元素执行的非干扰动作,因为它们是从流中消耗的,并且函数返回新的流。现在我们需要通过下面列出的干净Java程序通过其内部工作来了解 peek() 方法的生命周期如下:
Note:
- This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline.
- Since Java 9, if the number of elements is known in advance and unchanged in the stream, the .peek () statement will not be executed due to performance optimization. It is possible to force its operation by a command (formal) changing the number of elements eg. .filter (x -> true).
- Using peek without any terminal operation does nothing.
示例 1:
Java
// Java Program to Illustrate peek() Method
// of Stream class Without Terminal Operation Count
// Importing required classes
import java.util.*;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating a list of Integers
List list
= Arrays.asList(0, 2, 4, 6, 8, 10);
// Using peek without any terminal
// operation does nothing
list.stream().peek(System.out::println);
}
}
Java
// Java Program to Illustrate peek() Method
// of Stream class With Terminal Operation Count
// Importing required classes
import java.util.*;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating a list of Integers
List list
= Arrays.asList(0, 2, 4, 6, 8, 10);
// Using peek with count() method,Method
// which is a terminal operation
list.stream().peek(System.out::println).count();
}
}
输出:
从上面的输出中,我们可以感知到这段代码不会产生任何输出
示例 2:
Java
// Java Program to Illustrate peek() Method
// of Stream class With Terminal Operation Count
// Importing required classes
import java.util.*;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating a list of Integers
List list
= Arrays.asList(0, 2, 4, 6, 8, 10);
// Using peek with count() method,Method
// which is a terminal operation
list.stream().peek(System.out::println).count();
}
}
输出:
0
2
4
6
8
10