LongStream peek() es un método en java.util.stream.LongStream. 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:
LongStream peek(LongConsumer action) Where, LongStream is a sequence of primitive long-valued elements and the function returns a parallel LongStream and LongConsumer represents an operation that accepts a single long-valued argument.
Ejemplo 1: Realización de una suma en un flujo de rango dado.
// Java code for LongStream peek() // where the action performed is to get // sum of all elements in given range import java.util.*; import java.util.stream.LongStream; class GFG { // Driver code public static void main(String[] args) { // Creating a stream of longs LongStream stream = LongStream.range(2L, 10L); // performing action sum on elements of // given range and storing the result in sum long 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 LongStream peek() // where the action performed is to get // count of all elements in given range import java.util.*; import java.util.stream.LongStream; class GFG { // Driver code public static void main(String[] args) { // Creating a stream of longs LongStream stream = LongStream.range(2L, 10L); // 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 LongStream 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.LongStream; class GFG { // Driver code public static void main(String[] args) { // Creating a stream of longs LongStream stream = LongStream.range(2L, 10L); // 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