The following stream pipeline does not work if nothing is found, in which case .findFirst()
throws a NPE.
How can I prevent this?
scheduleDurationContainers.stream()
.filter(s -> s.getContainerType() == ScheduleIntervalContainerTypeEnum.BONUS).findFirst().get()
You can replace get()
with orElse(someDefault)
, which would return some default value if the Optional returned by findFirst
is empty. Or you can use orElseThrow(execptionSupplier)
if you want to throw some specific exception when findFirst
doesn't find anything.
If you want to return default value if there is nothing to return using lambda expression then you should use findAny() and orElse() in following sequence
Person result1 = persons.stream() // Convert to stream
.filter(x -> "answer".equals(x.getName())) // we want to filter "answer" only
.findAny() // If 'findAny' then return found
.orElse(null); // If not found, return null
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