A stream is created from o1 and o2. The filter method retains only the Optional instances that are present (i.e., non-empty). This results in a stream containing only o2.
The findAny method returns an Optional describing some element of the stream, or an empty Optional if the stream is empty. Since the stream contains o2, findAny returns Optional[Optional[1]].
The flatMap method is then used to flatten this nested Optional. It applies the provided mapping function (o -> o) to the value, resulting in Optional[1].
Finally, o3.orElse(2) returns the value contained in o3 if it is present; otherwise, it returns 2. Since o3 contains 1, the output is 1.
[Reference:, Optional.flatMap(Function) (Java SE 21 & JDK 21) - Oracle Help Center, , ]
Contribute your Thoughts:
Chosen Answer:
This is a voting comment (?). You can switch to a simple comment. It is better to Upvote an existing comment if you don't have anything to add.
Submit