Last active
May 22, 2019 15:41
-
-
Save Gabbendorf/bcb491711ab174f659cb84a36a6e780a to your computer and use it in GitHub Desktop.
Java Optional: example with .ifPresentOrElse()
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 void printMemberNameIfPresent(List<Member> members, int memberId) { | |
members.stream() | |
.filter(member -> member.getId() == memberId) | |
.findFirst() | |
.ifPresentOrElse( | |
member -> printMemberFullName(member.getFullName()), // if present, print successful message | |
() -> printNoMemberMessage(memberId) // if absent, print unsuccessful message | |
); | |
} | |
private static void printNoMemberMessage(int memberId) { | |
System.out.println(String.format("Member with id %d is not a member", memberId)); | |
} | |
private static void printMemberFullName(String memberFullName) { | |
System.out.println(String.format("The member's full name is %s", memberFullName)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment