# Use Optional::filter
# Description
Extracts an Optional::filter
(opens new window) from the consumer used in Optional::ifPresent
(opens new window).
Hence, simplifying the lambda expressions used with Optional
operations.
This transformation is feasible only if the entire consumer's body is wrapped into an if-statement.
# Benefits
Arguably, the lambda expression is easier to read and can be combined with other Optional
operations.
# Tags
# Code Changes
Pre
Optional<User> oUser = findById(userId);
oUser.ifPresent(user -> {
if (isSpecial(user)) {
sendMail(user.getMail());
}
});
Post
Optional<User> oUser = findById(userId);
oUser.filter(user -> isSpecial(user)).ifPresent(user -> {
sendMail(user.getMail());
});
# Limitations
Multiple Statements in Lambda Body - no transformation is feasible.
Pre
Optional<User> oUser = findById(userId);
oUser.ifPresent(user -> {
if (isSpecial(user)) {
sendPresent(user);
}
sendMail(user.getMail());
});
🛠️ Auto-refactor Available
You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:
Need help? Check out our installation guide.
# Properties
Property | Value |
---|---|
Rule ID | OptionalFilter |
First seen in jSparrow version | 3.14.0 |
Minimum Java version | 8 |
Remediation cost | 2 min |