简体   繁体   中英

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM