Skip to content

Instantly share code, notes, and snippets.

@Gabbendorf
Created May 22, 2019 14:36
Show Gist options
  • Save Gabbendorf/8a3cda5b16100633ac931c3de22817bd to your computer and use it in GitHub Desktop.
Save Gabbendorf/8a3cda5b16100633ac931c3de22817bd to your computer and use it in GitHub Desktop.
Java Optional: example with .filter() and .map()
public String nameOfActiveMemberById(List<Member> members, int memberId) {
return members.stream()
.filter(member -> member.getId() == memberId) // this is stream.filter
.findFirst() // gets Optional
.filter(Member::isActive) // if present, apply the predicate
.map(Member::getFullName) // if the output of predicate is true, get the full name
.orElseThrow(NoActiveMemberException::new); // if the output is false, throw an exception
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment