Guava - How to remove from a list, based on a predicate, keeping track of what was removed?

后端 未结 5 1719
清酒与你
清酒与你 2021-02-07 06:51

I have an ArrayList to be filtered, and various Guava Predicates to filter it with. This list will have only 50-100 elements.

I was planning on

5条回答
  •  忘掉有多难
    2021-02-07 07:47

    I'd investigate in observable predicates. The idea: everytime, a predicates apply method is about to return true, it will fire a notification to listeners:

    Iterable iterable = getIterable();
    Collection predicates = getPredicates();
    PredicatesLogger log = new PredicatesLogger(predicates);  // listens to all predicates
    for (ObservablePredicate pred : predicates) {
      Iterables.removeIf(iterable, pred);
      log.print();
      log.reset();
    }
    

    The ObservableLogger is a decorator for Predicate :

    public class ObservableLogger implements Predicate {
      private Predicate predicate;
    
      private List listeners = new ArrayList();
      // usual stuff for observer pattern
    
      @Override
      public boolean apply(Object input) {
        boolean result = predicate.apply(input);
        fire(result);
        return result;
      }
    
      // a fire method
    }
    

    The PredicateLogger needs one constructor that adds itself as a listener to the predicates. It will receive the notifications and cache the predicates that fired the events (the Event class needs an appropriate field for that information). print will create the log message, reset will clear the loggers cache (for the next run).

提交回复
热议问题