In Java, you can use the Optional
API to filter values based on a condition using the filter
method. The filter
method takes a predicate as an argument and applies it to the value contained in the Optional
. If the predicate evaluates to true
, the Optional
is returned unchanged. If the predicate evaluates to false
, an empty Optional
is returned.
Here’s an example:
Example:
package org.kodejava.util;
import java.util.Optional;
public class OptionalFilterExample {
public static void main(String[] args) {
// Create an Optional with a value
Optional<String> optionalValue = Optional.of("hello");
// Filter the Optional value based on a condition
Optional<String> filteredValue = optionalValue.filter(value -> value.length() > 3);
// If the value passes the filter, print it
filteredValue.ifPresent(System.out::println); // Output: hello
// Example where the filter does not match
Optional<String> emptyValue = optionalValue.filter(value -> value.length() > 10);
System.out.println(emptyValue.isPresent()); // Output: false
}
}
Explanation:
- Initial Value: The
Optional
is created with the value"hello"
. - Filtering: The
filter
method takes a predicate (value -> value.length() > 3
) and applies it to the contained value.- If the predicate is
true
(length is greater than 3), theOptional
retains the value. - If the predicate is
false
(e.g., length is less than 10), the result is an emptyOptional
.
- If the predicate is
- Accessing Results: The
ifPresent
method is used to print the value if it is still present, or useisPresent
to evaluate if the result is empty.
Summary:
- Use
Optional.filter(Predicate<T>)
to conditionally retain the value in anOptional
. - If the predicate fails, the
Optional
becomes empty. - Combine
Optional
withifPresent
,isPresent
, ororElse
to handle the filtered result.