Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 stream API orElse usage

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?

like image 555
Tyulpan Tyulpan Avatar asked Dec 04 '18 09:12

Tyulpan Tyulpan


People also ask

What is the use of orElse?

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.

What does orElse do in Java?

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.

What is the use of stream API in Java?

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.

What is orElse?

1. used to say what will happen if something is not done. You have to leave or else you will be arrested for trespassing.


1 Answers

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())
;
like image 88
Eran Avatar answered Oct 18 '22 23:10

Eran