IntStream findAny() method in Java

Java 8Object Oriented ProgrammingProgramming

The findAny() method of the IntStream class in Java is used to return an OptionalInt describing some element of the stream, or an empty OptionalInt if the stream is empty.

The syntax is as follows −

OptionalInt findAny()

Here, OptionalInt is a container object which may or may not contain an int value.

Create an IntStream and add some elements −

IntStream intStream = IntStream.of(20, 35, 50, 60, 80, 100);

Now, return any of the element of the stream using findAny() in Java −

OptionalInt res = intStream.findAny();

The following is an example to implement IntStream findAny() method in Java −

Example

 Live Demo

import java.util.*;
import java.util.stream.IntStream;

public class Demo {
   public static void main(String[] args) {
      IntStream intStream = IntStream.of(20, 35, 50, 60, 80, 100);
      OptionalInt res = intStream.findAny();
      if (res.isPresent()) {
         System.out.println(res.getAsInt());
      } else {
         System.out.println("Nothing!");
      }
   }
}

Output

20
raja
Published on 27-Mar-2019 13:18:31
Advertisements