IntStream findAny() con ejemplos

IntStream findAny() devuelve un OptionalInt (un objeto contenedor que puede o no contener un valor no nulo) que describe algún elemento de la secuencia, o un OptionalInt vacío si la secuencia está vacía.

Sintaxis:

OptionalInt findAny()

Where, OptionalInt is a container object which
may or may not contain a non-null value 
and the function returns an OptionalInt describing some element of
this stream, or an empty OptionalInt if the stream is empty.

Nota: findAny() es una operación de cortocircuito de terminal de la interfaz Stream. Este método devuelve cualquier primer elemento que satisfaga las operaciones intermedias. Esta es una operación de cortocircuito porque solo necesita que se devuelva ‘cualquier’ primer elemento y termine el resto de la iteración.

Ejemplo 1: método findAny() en Integer Stream.

// Java code for IntStream findAny()
// which returns an OptionalInt describing
// some element of the stream, or an
// empty OptionalInt if the stream is empty.
import java.util.*;
import java.util.stream.IntStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
        // Creating an IntStream
        IntStream stream = IntStream.of(6, 7, 8, 9);
  
        // Using IntStream findAny() to return
        // an OptionalInt describing some element
        // of the stream
        OptionalInt answer = stream.findAny();
  
        // if the stream is empty, an empty
        // OptionalInt is returned.
        if (answer.isPresent()) {
            System.out.println(answer.getAsInt());
        }
        else {
            System.out.println("no value");
        }
    }
}

Producción :

6

Nota: El comportamiento de la operación IntStream findAny() es explícitamente no determinista , es decir, es libre de seleccionar cualquier elemento en la secuencia. Varias invocaciones en la misma fuente pueden no devolver el mismo resultado.

Ejemplo 2: método findAny() para devolver los elementos divisibles por 4, de forma no determinista.

// Java code for IntStream findAny()
// which returns an OptionalInt describing
// some element of the stream, or an
// empty OptionalInt if the stream is empty.
import java.util.OptionalInt;
import java.util.stream.IntStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Creating an IntStream
        IntStream stream = IntStream.of(4, 5, 8, 10, 12, 16)
                               .parallel();
  
        // Using IntStream findAny().
        // Executing the source code multiple times
        // may not return the same result.
        // Every time you may get a different
        // Integer which is divisible by 4.
        stream = stream.filter(num -> num % 4 == 0);
  
        OptionalInt answer = stream.findAny();
        if (answer.isPresent()) {
            System.out.println(answer.getAsInt());
        }
    }
}

Producción :

16

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

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *