# Use Optional::map
# Description
Extracts an Optional::map
from the consumer used in Optional::ifPresent
.
This makes complicated code blocks easier to read and reuse.
# Benefits
Arguably, the lambda expression is easier to read and can be combined with other Optional
operations.
# Tags
# Code Changes
# Base Case
Pre
findById(userId)
.ifPresent(user -> {
String email = user.getMail();
sendMail(email);
});
Post
findById(userId)
.map(user -> user.getMail())
.ifPresent(email -> sendMail(email));
# Multiple Statements in Lambda Body
Pre
Optional<User> oUser = findById(userId);
oUser.ifPresent(user -> {
Address address = user.getAddress();
sendGiftCard(address);
sendAds(address);
});
Post
Optional<User> oUser = findById(userId);
oUser.map(user -> user.getAddress()).ifPresent(address -> {
sendGiftCard(address);
sendAds(address);
});
🛠️ 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 | OptionalMap |
First seen in jSparrow version | 3.13.0 |
Minimum Java version | 8 |
Remediation cost | 2 min |