Skip to content

Instantly share code, notes, and snippets.

@Gabbendorf
Last active May 22, 2019 15:41
Show Gist options
  • Save Gabbendorf/bcb491711ab174f659cb84a36a6e780a to your computer and use it in GitHub Desktop.
Save Gabbendorf/bcb491711ab174f659cb84a36a6e780a to your computer and use it in GitHub Desktop.
Java Optional: example with .ifPresentOrElse()
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