Composing Bi-Predicate in non-static context

347 views Asked by At

I have interface defined for all Filters:

public interface Filter<I, C> extends BiPredicate<I, C> {}

I inject in all these filter as a list in my Service class:

public class SomeClass {
    private List<BiPredicate<Status, Request>> filters;

    public List<Status> getStatus(final Request requestParameter) {
      final List<Status> summaries == this.repo
              .summary(requestParameter)
              .stream()
              .reduce(BiPredicate::and).orElse((x, y) -> true)
              .test();  //arg1=status from stream, arg2=requestParameter
  }
}

I am struggling to complete the above and apply all the filters from the collections filters. How do I pass status and requestParameter to test()? I am also getting an error non-static method cannot be referenced from static context?

Is there a better way than the following which is what I attempted:

  1. Initialise allFilters as field:

    private BiPredicate<Status, Request> allFilters = 
        filters.stream().reduce(BiPredicate::and).orElse((x, y) -> true);
    
  2. Then invoke call:

    this.repo.statusSummary(request)
        .stream()
        .filter(status -> applyFilters(status, request))
        .collect(toList());`
    

applyFilters():

private boolean applyFilters(Status status, Request request) {
    return this.allFilters.test(status, request);
}
2

There are 2 answers

2
Naman On

You might want to try allMatch as

final List<Status> summaries ==this.repo
        .summary(requestParameter)
        .stream()
        .filter(r -> filters.stream()
                .allMatch(f -> f.test(s, requestParameter)))
        .collect(Collectors.toList();
0
M06H On

Based on answer from this post

final List<Status> getStatus = this.repo
                .summary(request)
                .stream()
                .filter(status-> this.filters.stream().reduce(BiPredicate::and).orElse((x, y) -> true).test(status, request))
                .collect(toList());