Is it possible to add logging to removeIf in java 8?
collections, java, java-8, java-stream
Solution
If this is a recurring problem, you may create a helper method generalizing the task of decorating a predicate with another action, e.g. logging:
static <T> Predicate<T> logging(Predicate<T> p, BiConsumer<T,Boolean> log, boolean all) {
return t -> {
final boolean result = p.test(t);
if(all || result) log.accept(t, result);
return result;
};
}
which you may use like
public void testMethod(List<String> prop1, EmailJson randomModel){
prop1.forEach(s -> randomModel.getSomeList()
.removeIf(logging(model -> model.getSomeProp().equalsIgnoreCase(s),
(model,b) -> LOGGER.info(() -> "matched: "+model.getSomeProp()), false)));
}
though, in this specific case, it might be unnecessary to decorate the predicate itself, as `removeIf` return a `boolean` telling whether there were matches to remove, and the match value is still in scope:
public void testMethod(List<String> prop1, EmailJson randomModel){
prop1.stream().forEach(s -> {
if(randomModel.getSomeList()
.removeIf(model -> model.getSomeProp().equalsIgnoreCase(s)))
LOGGER.info(() -> "there were matches of: "+s);
});
}
Problem
I am using Java 8. The following code is working fine: ``` public void testMethod(List<String> prop1, EmailJson randomModel) { prop1.stream().forEach(s -> randomModel.getSomeList() .removeIf(model -> model.getSomeProp().equalsIgnoreCase(s))); } ``` Is it possible to log a message if the condition is true? I'm looking for something similar to: ``` public void testMethod(List<String> prop1, EmailJson randomModel) { prop1.stream().forEach(s -> randomModel.getSomeList() .removeIf(model -> model.getSomeProp().equalsIgnoreCase(s)) - > if this is true then log some action); } ```