alexcuesta

My tech blog

A misconception about streams on Java 8

leave a comment »

Have a look at this example:

return list.stream()
        .filter(item -> item.isValid())
        .findFirst()
        .orElse(failover()); 

private void failover() {
    // do something here
    // ...
    LOGGER.warn("Something happened");
}

Notice the call to “failover”. You may think this is only executed when the list does not actually have any valid elements in the list. However, this assumption is wrong.

The call to “failover” is always evaluated before executing the stream code. Therefore you will always see the log “Something happened” regardless of the list having valid or invalid elements.

The way to fix this is by using:

.orElseGet(() -> failover());

Thanks Nerses for spotting this🙂

Written by alexcuesta

March 24, 2016 at 11:07 am

Posted in Java

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: