Java 8 Optional - map and filter Examples
- schick09
- Apr 24, 2024
- 1 min read
Updated: Apr 25, 2024
We've talked about using java.util.Optional to avoid NullPointerException in production. Today we're going to talk about the map and filter features of the java.util.Optional package.
The map feature basically takes the current state of your Optional<T> object, applies a mapping function to it's value, and returns a new Optional<T> object with the new state. As always, if the present state of the value in the Optional is null or empty, it will return an empty Optional.
The filter feature takes the current state of your Optional<T> object and applies a predicate condition to that value. The predicate condition is a true or false condition. If the value is present and matches the predicate condition, a new Optional<T> object is returned containing only the value that matched the predicate. Again, if the value is null or empty, it will return an empty Optional.
For your reference, we have created a map and filter example you can take a look at here -- https://github.com/daveschickconsulting/java_8_examples/blob/main/src/funwithoptionals/MainExample.java

Comments