# Use Optional::filter

# Description

Extracts an Optional::filter (opens new window) from the consumer used in Optional::ifPresent (opens new window). Hence, simplifying the lambda expressions used with Optional operations. This transformation is feasible only if the entire consumer's body is wrapped into an if-statement.

# Benefits

Arguably, the lambda expression is easier to read and can be combined with other Optional operations.

# Tags

# Code Changes

Pre

Optional<User> oUser = findById(userId);
oUser.ifPresent(user -> {
	if (isSpecial(user)) {
		sendMail(user.getMail());
	}
});

Post

Optional<User> oUser = findById(userId);
oUser.filter(user -> isSpecial(user)).ifPresent(user -> {
	sendMail(user.getMail());
});

# Limitations

Multiple Statements in Lambda Body - no transformation is feasible.

Pre

Optional<User> oUser = findById(userId);
oUser.ifPresent(user -> {
	if (isSpecial(user)) {
		sendPresent(user);
	}
	sendMail(user.getMail());
});

Use a Java Refactoring Tool

Automate this Refactoring system-wide

You can apply this refactoring for free with the jSparrow Eclipse IDE plug-in.
Install the plug-in for Eclipse IDE: Eclipse Marketplace.

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

# Properties

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