有什么方法可以将列表流式传输 --> 映射 --> 过滤 --> 映射回列表的原始对象类型?
如果我们使用 foreach 来做,有如下解决方案:
List<Query> updatedQueries = getUpdatedQueries();
List<Query> finalQueries = new ArrayList<>();
updatedQueries.forEach(query -> {
Period period = getPeriodRequest(query);
boolean isValidPeriod = periodService.validatePeriodicity(period);
if(isValidPeriod && isMandatory(period)){
finalQueries.add(query);
}
});
但是有没有什么办法可以用下面的方法呢?
List<Query> updatedQueries = getUpdatedQueries();
List<Query> finalQueries = updatedQueries
.stream()
.map(this::getPeriodRequest) //returns the object of type Period
.filter(period->periodService.validatePeriodicity(period))
.filter(this::isMandatory)
//is any way we can map back to Query object (without any object translation function)
.collect(Collectors.toList());
最佳答案
试试这个
List<Query> finalQueries = updatedQueries
.stream().filter(query->{
Period period = getPeriodRequest(query);
return periodService.validatePeriodicity(period )&& isMandatory(period))
})
.collect(Collectors.toList());
关于java - 在 Java 8 中,有什么方法可以流式映射过滤器和映射回原始对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56034518/