findAny() isPresent() and ifPresent() example



import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class FinyAnyIsPresentIfPresentFlight {
public static void main(String[] args) {

List<Integer> nums = Arrays.asList(1,2,3,4,5,6,7);

Optional<Integer> result = nums
.stream()
.filter(num->num%2==0)
.findAny();

System.out.println("isPresent:"+result.isPresent());
System.out.println("resultVal: "+result.get());

nums.stream()
.filter(num->num%2==0)
.findAny()
.ifPresent(val->System.out.println("ifPresent: "+val));
}
}
Output:
isPresent:true
resultVal: 2
ifPresent: 2

Explanation:
findAny(): It find any element from the stream which match the given filter condition.

isPresent(): In result optional if the resulted value is available then it will give true else false.

result.get(): It returned the found element or it will give NoSuchElementException 

ifPresent(): The lamda expression given in this method gets executed if the provided filter condition match with any element in the stream.