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

前端 未结 2 1084
抹茶落季
抹茶落季 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<IEvent> isEligible();
    
        private Predicate<IEvent> internalIsEligible() {
            return iEvent -> {
                boolean res = isEligible().test(iEvent);
                if (!res) {
                    logger.info("event " + iEvent.toString() + " filtered by " + filterName);
                }
                return res;
            };
        }
    
        public List<IEvent> getFilteredEvents(final List<IEvent> 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.

    0 讨论(0)
  • 2021-01-12 03:06

    You can simply add brackets to your lambda expression and add the logging statement right before the validation :

    return event -> {
        // LOG.info(event.getName() + " was filtered...") or whatever you use for logging.
        return event.getPrizeCount() >= minimumNumOfPrizes;
    }
    

    Note that there exists a peek operation which is meant to be used mostly for logging on java streams :

    events.stream()
          .peek(event -> System.out.println("Filtering event" + event.getName()))
          .filter(isEligible())
          .collect(Collectors.toList());
    

    but that is not helping here, as you need to log in AbstractEventFilter implementations.

    0 讨论(0)
提交回复
热议问题