Java 中的 IntStream peek() 方法
java 8programmingobject oriented programming
Java 中 IntStream 类的 peek() 方法返回一个由该流的元素组成的流。当从结果流中消费元素时,它还会对每个元素执行提供的操作。
语法如下
IntStream peek(IntConsumer action)
此处,参数 action 是在从流中消费元素时对元素执行的互不干扰的操作。IntConsumer 表示接受单个 int 值参数且不返回结果的操作。
以下是在 Java 中实现 IntStream peek() 方法的示例
示例
import java.util.*; import java.util.stream.IntStream; public class Demo { public static void main(String[] args) { IntStream intStream = IntStream.range(50, 60); System.out.println("Elements in the stream = "); long res = intStream.peek(System.out::println).count(); System.out.println("Count of elements = " + res); } }
输出
Elements in the stream = 50 51 52 53 54 55 56 57 58 59 Count of elements = 10