# Use Optional::ifPresent

# Description

The usage of Optional.get should be avoided in general because it can potentially throw a NoSuchElementException (it is likely to be deprecated in future releases). It is often the case that the invocation of Optional.get is wrapped by a condition that uses Optional.isPresent. Such cases can be replaced with the Optional.ifPresent(Consumer<? super T> consumer).

# Benefits

Improves readability and enables the use of higher order functions on Optional.

# Tags

# Code Changes

# Default

Pre

public void defaultUseCase_shouldTransform(Optional<String> input) {
    if (input.isPresent()) {
        String value = input.get();
        System.out.println(value);
    }
}

Post

public void defaultUseCase_shouldTransform(Optional<String> input) {
    input.ifPresent(value -> System.out.println(value));
}

# Multiple initializes in the row

Pre

String value = "prefix" + "value" + "suffix";
public void multipleInitializers_shouldTransform(Optional<String> input) {
    if (input.isPresent()) {
        String value = input.get(), second = "";
        System.out.println(value);
        System.out.println(second);
    }
}

Post

String value = "prefix" + "value" + "suffix";
public void multipleInitializers_shouldTransform(Optional<String> input) {
    input.ifPresent(value -> {
        String second = "";
        System.out.println(value);
        System.out.println(second);
    });
}

# Limitations

Can not be applied if the then path of the branch contains a non-effectively final variable or contains unhandled exceptions.

🛠️ Auto-refactor Available

You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:

Drag to your running Eclipse* workspace. *Requires Eclipse Marketplace Client

Need help? Check out our installation guide.

# Properties

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