# Use Optional::ifPresent

# Properties

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

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

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

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? 😊