Logging the result of filter while using java streams filter by predicate

前端 未结 2 1087
抹茶落季
抹茶落季 2021-01-12 02:37

The scenario is there are different types of filters I have created which filters the list of some objects based on the property of the object.

So for that I have

2条回答
  •  花落未央
    2021-01-12 02:45

    perhaps not the prettiest solution, but it works and you only change your abstract base class:

    abstract class AbstractEventFilter {
    
        private final Logger logger = Logger.getLogger(getClass().getCanonicalName());
        private final String filterName = getClass().getSimpleName();
    
        protected abstract Predicate isEligible();
    
        private Predicate internalIsEligible() {
            return iEvent -> {
                boolean res = isEligible().test(iEvent);
                if (!res) {
                    logger.info("event " + iEvent.toString() + " filtered by " + filterName);
                }
                return res;
            };
        }
    
        public List getFilteredEvents(final List events) {
            return events.stream().filter(internalIsEligible()).collect(Collectors.toList());
        }
    }
    

    you keep your derived classes implementing isELigible() as before, only in your getFilteredEvents method, you call the internalIsEligibable method instead.

提交回复
热议问题