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 that I want it to return nullif the value does not exist, how would I go about it? As he stands, he simply throws NoSuchElementException.

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

The method findFirst()returns Optional<Player>.

If the option has a player object, optional.get()will return that object. If the object does not exist and you need an alternative, specify this option in

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

See Supplementary Documentation and Supplementary Tutorial for more details.

+11
source

Source: https://habr.com/ru/post/1627622/


All Articles