Using Java8 streams to filter list and get the first element

Viewed 1706
 collectorConfiguration = Optional.ofNullable(recapPlacement.getPnetCode())
                    .map(pnetCode -> Optional.ofNullable(collectorConfigurations.stream()
                    .filter(c -> pnetCode.equals(c.getPnetCode()))
                    .collect(Collectors.toList())
                    .stream().filter(Objects::nonNull).findFirst())
                    .orElse(unknownExternalCollector))
                    .orElse(unknownExternalCollector);

Here in the above code

1) I want to return unknownExternalCollector if pnetCode is null OR

2) I want to iterate collectorConfigurations and find atleast one record by using pnetCode, if there are no elements in the list that matches pnetCode then I want return unknownExternalCollector. I am getting compilation error saying

orElse
(java.util.Optional<com.capitalone.omega.collectorservice.domain.CollectorConfiguration>)
in Optional cannot be applied om.capitalone.omega.collectorservice.domain.CollectorConfiguration
1 Answers

You can simplify it as follows (there is no need to collect and then stream and call findFirst. You can use flatMap here)

collectorConfiguration = Optional.ofNullable(recapPlacement.getPnetCode())
            .flatMap(pnetCode -> collectorConfigurations.stream()
                    .filter(c -> pnetCode.equals(c.getPnetCode()))
                    .filter(Objects::nonNull)
                    .findFirst())
            .orElse(unknownExternalCollector);
Related