Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I avoid two filters when condition involves an Optional

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?

like image 527
andydavies Avatar asked Jun 10 '21 08:06

andydavies


People also ask

Is filter present in optional class?

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.

Can we have multiple filter in stream?

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) .

Can we have multiple filter in stream Java?

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).


2 Answers

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.

like image 155
ernest_k Avatar answered Oct 17 '22 15:10

ernest_k


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();
like image 2
Karol Dowbecki Avatar answered Oct 17 '22 13:10

Karol Dowbecki