Java 8 stream API orElse usage
It might be more readable with ternary conditional operator:
return users.stream()
.filter(user -> id.equals(user.getId()))
.map(
user -> (user.getData() != null)
? user.getData()
: emptyMap()
)
.collect(Collectors.toList())
;
In order to use orElse
you'll have to create an Optional
that wraps user.getData()
. I'm not sure that's a good idea.
If you insist on using orElse
(or even better, orElseGet
, to avoid evaluating emptyMap()
when it's not required), it can look like this:
return users.stream()
.filter(user -> id.equals(user.getId()))
.map(
user -> Optional.ofNullable(
user.getData()
).orElseGet(
() -> emptyMap()
)
)
.collect(Collectors.toList())
;
As I pointed out in the comments as well and I highly doubt that you might just be looking for the following
users
.stream()
.filter(
user -> id.equals(user.getId())
&& (user.getData() != null)
)
.map(User::getData)
.collect(Collectors.toList())
;
But then the question isn't clear enough to say what is the eventual return type of your statement is or what is the emptyMap
used in your code! Hence I highly doubt, if you even need an Optional
API in first place for this operation.
Note: The above-stated solution does assume that emptyMap
is Collections.emptyMap
which I am not sure why would one want to collect in a data structure which is denoted as List<Map<K,V>>
.