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

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.

a drawn cute bird pointing at a graph that shows positive results

# Properties

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