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

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