Java 8 stream api orElse usage

  • A+

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             .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 I cannot use orElse in this case?


It might be more readable with ternary conditional operator:

return   .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   .filter(user -> id.equals(user.getId()))   .map(user -> Optional.ofNullable(user.getData()).orElseGet(() -> emptyMap())))   .collect(Collectors.toList()); 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: