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

后端 未结 5 1635
清酒与你
清酒与你 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:44

    I agree with Peter's anwser.

    But if you want to have fun, you could also wrap each of your predicate inside a predicate which would delegate to the wrapped predicate, and store the values for which true is returned inside a Map> removedByPredicate :

    class PredicateWrapper implements Predicate {
        private Predicate delegate;
    
        public PredicateWrapper(Predicate delegate) {
            this.delegate = delegate;
        }
    
        @Override
        public boolean apply(Foo foo) {
            boolean result = delegate.apply(foo);
            if (result) {
                List objectsRemoved = removedByPredicate.get(delegate);
                if (objectsRemoved == null) {
                    objectsRemoved = Lists.newArrayList();
                    removedByPredicate.put(delegate, objectsRemoved);
                }
                objectsRemoved.add(foo);
            }
            return result;
        }
    }
    

提交回复
热议问题