当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Stream peek()用法及代码示例


在 Java 中,Stream 提供了一种强大的数据处理替代方法,在这里我们将讨论一种非常常用的方法,名为peek() 这是消费者行为本质上返回一个由该流的元素组成的流,另外在从结果流中消耗元素时对每个元素执行提供的操作。这是一中间操作,因为它创建一个新流,在遍历时,该新流包含与给定谓词匹配的初始流的元素。

用法:

Stream<T> 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<Integer> list
            = Arrays.asList(0, 2, 4, 6, 8, 10);
        // Using peek without any terminal
        // operation does nothing
        list.stream().peek(System.out::println);
    }
}


输出:

从上面的输出我们可以看出这段代码不会产生任何输出

示例 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<Integer> 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


相关用法


注:本文由纯净天空筛选整理自Sahil_Bansall大神的英文原创作品 Stream peek() Method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。