# Use Optional::map

# Properties

Property Value
Rule ID OptionalMap
First seen in jSparrow version 3.13.0
Minimum Java version 8
Remediation cost 2 min

# 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.

# 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);
    });

Automatic Application of This Rule

The automatic application of this rule is supported in the following jSparrow version:

# Tags

1
default
You & jSparrow
default

Hey there! May I help you? 😊