# Use Optional::ifPresentOrElse

# Description

It is common to have an else-statement following an Optional.isPresent check. One of the extensions of the Optional API in Java 9 is Optional.ifPresentOrElse (opens new window), which performs either a Consumer or a Runnable depending on the presence of the value. This rule replaces an isPresent check followed by an else-statement with a single ifPresentOrElse invocation.

Requirements

Java 9

# Benefits

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

# Tags

# Code Changes

# Default

Pre

if(optional.isPresent()) {
	String value = optional.get();
	consume(value);
} else {
	consume("No value");
}

Post

		optional.ifPresentOrElse(value -> consume(value), () -> consume("No value"));

# Multiple Statements Lambda Body

Pre

Optional<User> optional = findById(id);
if(optional.isPresent()) {
	User user = optional.get();
	consume(user);
	consume(user);
} else {
	System.out.println();
	noUserFound();
}

Post

Optional<User> optional = findById(id);
optional.ifPresentOrElse(user -> {
	consume(user);
	consume(user);
}, () -> {
	System.out.println();
	noUserFound();
});

# Limitations

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

int i = 0;
i++;
if(optional.isPresent()) {
	String value = optional.get();
	consume(value);
	i++;
} else {
	consume("No value");
}

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 OptionalIfPresentOrElse
First seen in jSparrow version 3.10.0
Minimum Java version 9
Remediation cost 2 min