Java Streams - IntStream findAny() example








IntStream findAny() returns an OptionalInt describing some element of the stream, or an empty OptionalInt if the stream is empty.

Syntax

findAny has the following syntax.

OptionalInt findAny()

Example

The following example shows how to use findAny.

import java.util.OptionalInt;
import java.util.stream.IntStream;
/*w w  w.j  a  v  a  2  s.  c  o m*/
public class Main {
  public static void main(String[] args) {
    IntStream i = IntStream.of(1, 2, 3, 4);
    OptionalInt n = i.findAny();
    if(n.isPresent()){
      System.out.println(n.getAsInt());
    }else{
      System.out.println("noValue");
    }
  }
}

The code above generates the following result.