# Use Optional::filter

# Properties

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

# Description

Extracts an Optional::filter from the consumer used in Optional::ifPresent. 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.

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

Automatic Application of This Rule

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

# Tags

1
default
You & jSparrow
default

Hey there! May I help you? 😊