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?
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>.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With