Reputation: 956
I am trying to use a Stream
in orElse
and having difficulty in understanding the error.
collectorConfiguration = Optional.ofNullable(recapPlacement.getAttId())
.map(attId -> Optional.ofNullable(processorEngine.buildFrimFromAttId(attId))
.orElseThrow( () -> new OmegaException("UnableToFirmByAttId", recapPlacement.getAttId())))
.orElse( () -> Optional.ofNullable(collectorConfigurations.stream() //getting error here
.filter(cc -> recapPlacement.getPnetCode().equals(cc.getPnetCode()))
.filter(Objects::nonNull)
.findFirst())
.orElseThrow( () -> new OmegaException("CollectorCouldNotMapForPnetCode", recapPlacement.getPnetCode()))
);
Overall in the above code I am trying to
get collectorConfig
if attId
is not null
if attId
is not null and collectorConfig
not found for that attId
then I am throwing exception
if attId
is null then I am using pnet
code to get collectConfig
by streaming collectConfigurations
list
if collectConfig
is not found for pnetCode
then I am throwing exception
It is giving a compilation error 'Target type of a lambda expression must be an interface
' in the orElse
block.
Upvotes: 3
Views: 1228
Reputation: 31878
You might want to replace
.orElse( () -> Optional.ofNullable(collectorConfigurations.stream() //getting error here
with Optional.orElseGet
which expects a Supplier
as :
.orElseGet( () -> Optional.ofNullable(collectorConfigurations.stream() ...
In addition to the above, you shouldn't need the Optional.ofNullable
in the supplier
.orElseGet( () -> collectorConfigurations.stream()
.filter(cc -> recapPlacement.getPnetCode().equals(cc.getPnetCode()))
.filter(Objects::nonNull) //non-null filtered
.findFirst()) // optional
.orElseThrow( () -> new OmegaException("CollectorCouldNotMapForPnet...
Upvotes: 4
Reputation: 2890
orElse
takes a regular value, not anything that could be represented by a lambda. Simply removing the () ->
should help. Alternatively, you might have meant to call orElseGet
Upvotes: 1