IntStream peek() es un método en java.util.stream.IntStream. La función devuelve una secuencia que consta de los elementos de esta secuencia y, además, realiza la acción proporcionada en cada elemento a medida que se consumen elementos de la secuencia resultante.
Sintaxis:
IntStream peek(IntConsumer action) Where, IntStream is a sequence of primitive int-valued elements and the function returns a parallel IntStream and IntConsumer represents an operation that accepts a single int-valued argument.
Ejemplo 1: Realización de una suma en un flujo de rango dado.
// Java code for IntStream peek() // where the action performed is to get // sum of all elements in given range import java.util.*; import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating a stream of integers IntStream stream = IntStream.range(2, 10); // performing action sum on elements of // given range and storing the result in sum int sum = stream.peek(System.out::println).sum(); // Displaying the result of action performed System.out.println("sum is : " + sum); } }
Producción :
2 3 4 5 6 7 8 9 sum is : 44
Ejemplo 2: Realización de una operación de conteo en un flujo de rango dado.
// Java code for IntStream peek() // where the action performed is to get // count of all elements in given range import java.util.*; import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating a stream of integers IntStream stream = IntStream.range(2, 10); // performing action count on elements of // given range and storing the result in Count long Count = stream.peek(System.out::println).count(); // Displaying the result of action performed System.out.println("count : " + Count); } }
Producción :
2 3 4 5 6 7 8 9 count : 8
Ejemplo 3: Realización de una operación promedio en un flujo de rango dado.
// Java code for IntStream peek() // where the action performed is to get // average of all elements in given range import java.util.*; import java.util.OptionalDouble; import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating a stream of integers IntStream stream = IntStream.range(2, 10); // performing action average on elements of // given range and storing the result in avg OptionalDouble avg = stream.peek(System.out::println) .average(); // If a value is present, isPresent() // will return true, else -1 is displayed. if(avg.isPresent()) { System.out.println("Average is : " + avg.getAsDouble()); } else { System.out.println("-1"); } } }
Producción :
2 3 4 5 6 7 8 9 Average is : 5.5
Publicación traducida automáticamente
Artículo escrito por Sahil_Bansall y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA