ehsan ehsan - 3 months ago 9x
Java Question

Is it required to use orElse(null) in Streams?

I used this code snippet to find the first item in the String List which contained

character :

List<String> words = Arrays.asList("hi", "hello", "bye", "goodbye");
String s1 = -> word.contains("o")).findFirst().orElse(null);

So this finds the first item that has
(hello) and if it doesn't find anything it will return
as specified by
. So my question is :

Is it really necessary to use
and if I don't specify it what will it return as default if it doesn't find any matches?


findFirst returns an Optional. You need to use one of the orElse methods to get an actual value from it.