Sabbullo
Sabbullo

Reputation: 1

Retrieve stream from Optional<Stream>

How can I get the actual stream in order to filter or map methods from an Optional ? For instance

Optional.ofNullable(id)
        .map(this:loadAllById) // method loadAllById return a stream (now is wrapped in Optional<Stream>)
        .filter(obj -> obj.status) // here i have no access to object in stream but to the full stream 

From this a doubt also arises. Is it correct to have a stream inside an Optional? Since the stream should always be not null (in case empty) shouldn't the check be needed?

Upvotes: 0

Views: 1279

Answers (2)

Nolle
Nolle

Reputation: 271

Try this

Optional.ofNullable(id)
        .stream()       // Java 9
        .flatMap(this::loadAllById)
        .filter(...)

Upvotes: 0

Alexander Ivanchenko
Alexander Ivanchenko

Reputation: 29058

Here, you don't need to use Optinal at all.

Optional was not designed to perform null-checks and Optional.ofNullable(id) is an abuse of optional (see Should Optional.ofNullable() be used for null check?). Use an explicit null-check instead.

An empty stream can represent the absence of data, you don't need an empty optional for that. Make your method loadAllById() return a stream Stream<Foo> instead of optional of stream Optional<Stream<Foo>>. Wrapping a stream with an optional isn't a proper usage of optional (as it has been already mentioned in the comments by @MC Emperor).

That's how your code might look like:

public Stream<Foo> getFoosById(Long id, Status status) {
    if (id == null) {
        return Stream.empty();
    }
    
    return loadAllById(id).filter(foo -> foo.getStatus().equals(status));
}

If status is an enum you can check reference equality with ==.

Upvotes: 6

Related Questions