Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Stream API: Optional if not null proceed

I would like to have opportunity to make null check inside the stream:

firstItem = array.stream().min(myComparator).get();
if(firstItem!=null){
     name = firstItem.getData().get("Name")
}

Is it possible to get name right from the Stream?

like image 937
Rudziankoŭ Avatar asked May 22 '26 00:05

Rudziankoŭ


1 Answers

Note that Optional can't contain null values, so your code will either execute the conditional, or fail with an exception at get().

You could change the get() to orElse(null); but you'd still need the separate conditional.

Instead, use Optional.map, then orElse:

String name = 
    array.stream()
        .min(myComparator)
        .map(m -> m.getData().get("name"))
        .orElse(someDefaultValue);

Of course, if you don't want to assign a default value, you can omit the final orElse, and make the variable type Optional<String>.

like image 155
Andy Turner Avatar answered May 23 '26 14:05

Andy Turner