3

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);
}
ernest_k
  • 44,416
  • 5
  • 53
  • 99
M06H
  • 1,675
  • 3
  • 36
  • 76
  • By "better", do you mean a way to do it in one statement? – ernest_k Jan 30 '20 at 10:43
  • by better I mean to say to avoid initialising `allFilters` as class variable and instead combine the functions in the method and test and return the result. – M06H Jan 30 '20 at 10:46
  • 3
    In my opinion, what you've implemented is better than what you're looking for. – ernest_k Jan 30 '20 at 10:50

2 Answers2

0

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();
Naman
  • 27,789
  • 26
  • 218
  • 353
  • is call to `allMatch()` do exactly same as my answer ? It will apply and check against all defined filters ? – M06H Jan 30 '20 at 10:57
  • @M06H yes it would `test` for all existing filters in the list. – Naman Jan 30 '20 at 12:07
0

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());
M06H
  • 1,675
  • 3
  • 36
  • 76