當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。