ImTomRS
ImTomRS

Reputation: 371

Java 8 - Stream, filter and optional

I have the following code

public Player findPlayerByUsername(String username) {
    return players.stream().filter(p -> p.getUsername().equalsIgnoreCase(username))
                  .findFirst().get();
}

The problem is, I want it to return null if no value is present, how would I go amongst doing that? Because as it stands, that just throws a NoSuchElementException.

Upvotes: 4

Views: 3664

Answers (1)

Noor Nawaz
Noor Nawaz

Reputation: 2225

public Player findPlayerByUsername(final String username) {
   return players.stream().filter(p -> p.getUsername().equalsIgnoreCase(username)).findFirst().orElse(null);
}

The findFirst() method returns an Optional<Player>.

If optional has player object, optional.get() will return that object. If object doesn't exist and you want some alternative, give that option in

.orElse(new Player()); or .orElse(null) 

For more details see Optional Documentation and Optional tutorial

Upvotes: 11

Related Questions