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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With