gpt4 book ai didi

java - 在 Java 8 中,有什么方法可以流式映射过滤器和映射回原始对象吗?

转载 作者:搜寻专家 更新时间:2023-11-01 01:12:03 25 4
gpt4 key购买 nike

有什么方法可以将列表流式传输 --> 映射 --> 过滤 --> 映射回列表的原始对象类型?

如果我们使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com