The findAny() method of the Java Stream returns an Optional for some element of the stream or an empty Optional if the stream is empty. Here, Optional is a container object which may or may not contain a non-null value.
Following is an example to implement the findAny() method in Java −
Example
import java.util.*;
public class Demo {
public static void main(String[] args){
List<Integer> list = Arrays.asList(10, 20, 30, 40, 50);
Optional<Integer> res = list.stream().findAny();
if (res.isPresent()) {
System.out.println(res.get());
} else {
System.out.println("None!");
}
}
}Output
10
Example
Let us see another example with list of strings −
import java.util.*;
public class Demo {
public static void main(String[] args) {
List<String> myList = Arrays.asList("Kevin", "Jofra","Tom", "Chris", "Liam");
Optional<String> res = myList.stream().findAny();
if (res.isPresent()) {
System.out.println(res.get());
} else {
System.out.println("None!");
}
}
}Output
Kevin