What I'm trying to do is to filter the list, then map it and use orElse
if null
and then collect it back to the list. Now I can achieve it this way:
return users.stream()
.filter(user -> id.equals(user.getId()))
.map(
user -> {
if(user.getData() != null) {
return user.getData();
}
return Collections.emptyMap();
}
)
.collect(Collectors.toList());
But the question is: how can I make this structure better and why cannot I use orElse
in this case?
What is the orElse() method of the Optional class? The orElse() method will return the value present in an Optional object. If the value is not present, then the passed argument is returned.
orElse(): returns the value if present, otherwise returns other. orElseGet(): returns the value if present, otherwise invokes other and returns the result of its invocation.
Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.
1. used to say what will happen if something is not done. You have to leave or else you will be arrested for trespassing.
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())
;
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