Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 477
ImTomRS Avatar asked Dec 19 '22 19:12

ImTomRS


1 Answers

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

like image 176
Noor Nawaz Avatar answered Dec 21 '22 11:12

Noor Nawaz