使用java stream过滤谓词时记录过滤器的结果 [英] Logging the result of filter while using java streams filter by predicate
问题描述
场景是我创建了不同类型的过滤器,它们根据对象的属性过滤一些对象的列表。
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.
所以为此我创建了一个每个过滤器继承的AbstractObjectFilter类。
AbstractObjectFilter.java
So for that I have created an AbstractObjectFilter class which inherited by every filter.
AbstractObjectFilter.java
public abstract class AbstractEventFilter
{
protected abstract Predicate<IEvent> isEligible();
public List<IEvent> getFilteredEvents(final List<IEvent> events)
{
return events.stream().filter(isEligible()).collect(Collectors.toList());
}
}
所以现在每个过滤器都会扩展此类并覆盖isEligible ()并在该函数中,它根据其属性返回谓词。
So now every filter extends this class and overrides the isEligible() and in that function it returns the predicate based on its properties.
例如: -
MinNumOfPrizesFilter.java
For eg:- MinNumOfPrizesFilter.java
public class MinimumNumOfPrizesFilter extends AbstractEventFilter
{
private int minimumNumOfPrizes;
public MinimumNumOfPrizesFilter(@NonNull int minimumNumOfPrizes)
{
this.minimumNumOfPrizes = minimumNumOfPrizes;
}
@Override
protected Predicate<IEvent> isEligible()
{
return event -> event.getPrizeCount() >= minimumNumOfPrizes;
}
}
同样,我创建了许多其他过滤器。有一个applyFilter函数迭代过滤器对象列表,并通过调用getFilteredEvents函数继续应用过滤器。
Similarly there are many other filters I have created. There is one applyFilter function which iterate over the list of filter objects and keep applying filter by call getFilteredEvents function.
现在我如何记录每个事件的命运例如 - x1事件由MinNumOfPrizesFilter过滤器过滤.x1的奖金数量 - 10,所需的最低奖金数量 - 20
Now how can i log the fate of each event For example - "x1 event was filtered by MinNumOfPrizesFilter filter. x1's prize count - 10 , required min prize count - 20"
推荐答案
你可以简单地在lambda表达式中添加括号并在验证之前添加日志记录语句:
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;
}
请注意,存在 peek
主要用于登录java流的操作:
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());
但这在这里没有帮助,因为你需要登录 AbstractEventFilter
implements。
but that is not helping here, as you need to log in AbstractEventFilter
implementations.
这篇关于使用java stream过滤谓词时记录过滤器的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!