Created
May 22, 2019 14:34
-
-
Save Gabbendorf/4a40ab0360bc5278a3c73f02250fcc54 to your computer and use it in GitHub Desktop.
Java Optional: example with .map() and .orElse()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public String memberNameById(List<Member> members, int memberId) { | |
return members.stream() | |
.filter(member -> member.getId() == memberId) | |
.findFirst() // returns an Optional | |
.map(Member::getName) // transforms the value if present in the Optional | |
.orElse("UNKNOWN"); // if the Optional is absent, it returns a default value | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment