Created
May 22, 2019 14:36
-
-
Save Gabbendorf/8a3cda5b16100633ac931c3de22817bd to your computer and use it in GitHub Desktop.
Java Optional: example with .filter() and .map()
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 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