# 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);
});
You Want To Have Those Changes Done Automatically?
The automatic application of this rule is supported in the following jSparrow version:
# Properties
Property | Value |
---|---|
Rule ID | OptionalMap |
First seen in jSparrow version | 3.13.0 |
Minimum Java version | 8 |
Remediation cost | 2 min |