The java.util.Optional
class in Java provides a filter
method. It’s used to apply a condition on the value held by this Optional
.
Here is an example of how to use Optional
‘s filter
method:
package org.kodejava.util;
import java.util.Optional;
public class OptionalFilter {
public static void main(String[] args) {
// Creating Optional object and assigning a value
Optional<String> myOptional = Optional.of("Hello");
// Applying filter method on Optional
Optional<String> result = myOptional.filter(value -> value.length() > 5);
// Print the result
// This will not print anything because the length of "Hello"
// is not greater than 5.
result.ifPresent(System.out::println);
}
}
In this example, the filter
method is used to apply a condition on the value held by this myOptional
object. The condition is that the length of the value should be greater than 5. If the value satisfies the condition, it is returned. Otherwise, an empty Optional
object is returned.
The ifPresent
method is used to print the value held by this Optional
, if it is non-empty. This particular use of filter
will not print anything because the string “Hello” length is not greater than 5.
You can use isEmpty
method to check whether Optional
is empty.
if (result.isEmpty()) {
System.out.println("The Optional is empty");
}
In this case, it would print “The Optional is empty”.
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024