# Use Optional::ifPresentOrElse

# Properties

Property Value
Rule ID OptionalIfPresentOrElse
First seen in jSparrow version 3.10.0
Minimum Java version 9
Remediation cost 2 min

# 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, 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. E.g.:

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

is transformed to:

		Optional<User> optional = findById(id);
		optional.ifPresentOrElse(
            user -> consume(user), 
            () -> noUserFound());

# Benefits

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

# Requirement & Tags

Requirements

Java 9

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

Automatic Application of This Rule

The automatic application of this rule is supported in the following jSparrow version: