I have code like this:
myList.stream()
.filter(item -> item.getName().isPresent())
.filter(item -> item.getName().get().equalsIgnoreCase(otherName))
.findFirst();
(... where item.getName()
has a return type of Optional<String>
)
How can I condense two filters into one here?
The filter() method of java. util. Optional class in Java is used to filter the value of this Optional instance by matching it with the given Predicate, and then return the filtered Optional instance.
Combining two filter instances creates more objects and hence more delegating code but this can change if you use method references rather than lambda expressions, e.g. replace filter(x -> x. isCool()) by filter(ItemType::isCool) .
2. Java stream filter multiple conditions. One of the utility method filter() helps to filter the stream elements based on a given predicate. The predicate is a functional interface that takes a single element as an argument and evaluates it against a specified condition).
You can use Optional.filter()
:
myList.stream()
.filter(item ->
item.getName().filter(n -> n.equalsIgnoreCase(otherName)).isPresent())
.findFirst();
The inner filter
call is Optional.filter
, which returns an empty optional if the filter condition was not met.
You can avoid it with Optional::stream()
method:
If a value is present, returns a sequential Stream containing only that value, otherwise returns an empty Stream.
myList.stream()
.map(Item::getName)
.flatMap(Optional::stream)
.filter(otherName::equalsIgnoreCase)
.findFirst();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With