Skip to content

Instantly share code, notes, and snippets.

@Gabbendorf
Created May 22, 2019 14:34
Show Gist options
  • Save Gabbendorf/4a40ab0360bc5278a3c73f02250fcc54 to your computer and use it in GitHub Desktop.
Save Gabbendorf/4a40ab0360bc5278a3c73f02250fcc54 to your computer and use it in GitHub Desktop.
Java Optional: example with .map() and .orElse()
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