java stream peek_Java Stream peek()用法及代码示例

Stream peek(Consumer action)返回由该流的元素组成的流,并在从结果流中消耗元素时对每个元素执行附加的操作。这是一个中间操作,即它创建了一个新的流,该流在遍历时将包含与给定谓词匹配的初始流的元素。

用法:

Stream peek(Consumer super T> action)

Where, Stream is an interface and T is the type of

stream elements. action is a non-interfering action

to perform on the elements as they are consumed

from the stream and the function returns the new stream.

注意:

存在此方法主要是为了支持调试,您需要在其中查看元素流过管道中特定点的情况。

从Java 9开始,如果元素的数量预先已知并且在流中保持不变,则由于性能优化,将不会执行.peek()语句。可以通过命令(正式)更改元素数量(例如, .filter(x-> true)。

在没有任何终端操作的情况下使用peek不会执行任何操作。

示例1:无需终端操作即可查看。

// Implementation of Stream.peek()

// in Java 8

import java.util.*;

class GFG {

// Driver code

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. Hence this

// code will produce no output.

list.stream().peek(System.out::println);

}

}

输出:

No Output

示例2:查看终端操作计数。

// Implementation of Stream.peek()

// in Java 8

import java.util.*;

class GFG {

// Driver code

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(), which

// is a terminal operation

list.stream().peek(System.out::println).count();

}

}

输出:

0

2

4

6

8

10

你可能感兴趣的:(java,stream,peek)