Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java 8 stream - handle if nothing is found

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()
like image 572
quma Avatar asked Apr 07 '16 08:04

quma


2 Answers

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.

like image 134
Eran Avatar answered Nov 02 '22 00:11

Eran


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
like image 27
Amar Magar Avatar answered Nov 02 '22 00:11

Amar Magar