# 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);
});
Use a Java Refactoring Tool
No license required
You can review this refactoring on your code without a license by installing jSparrow to your Eclipse IDE. Install the plug-in from Eclipse IDE: Eclipse Marketplace.
System-wide Refactoring
Do you want to automate this refactoring (and many more) to your system-wide code? The automatic application of this system-wide refactoring can be unlocked by acquiring your jSparrow license.
# Properties
Property | Value |
---|---|
Rule ID | OptionalMap |
First seen in jSparrow version | 3.13.0 |
Minimum Java version | 8 |
Remediation cost | 2 min |