stream() method of Optional object in Java

This method is supported since Java 9.

This method is used to create a new Stream object from an Optional object in Java.

If the Optional object contains a value, this method will return the Stream object containing that value, otherwise, it returns an empty Stream object.

For example:

Result:

stream() method of Optional object in Java

In the case where we have a List of Optional objects, one of them is empty, the stream() method of the Optional object can help us remove these Optional empty objects.

For example:

You can refer to the flatMap() method of the Stream object here.

Result:

stream() method of Optional object in Java

 

Add Comment