gpt4 book ai didi

java - 使用 java8 流的规范列表组合

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:00:42 27 4
gpt4 key购买 nike

如何为这段代码使用 Java8 流:

Specification<T> specification = specifications.getSpec(searchCriteria.getConditions().get(0));
for(int i = 1; i < searchCriteria.getConditions().size(); i++) {
specification = specification.and(getSpec(searchCriteria.getConditions().get(i)));
}

使用流:

  IntStream.range(1,searchCriteria.getConditions().size())
.mapToObj(index-> getSpec(searchCriteria.getConditions().get(index)))
.collect();//how to merge with calling and

相关类&&方法:

@Getter
@Setter
public class SearchCriteria implements Serializable{

private static final long serialVersionUID = 1L;

private List<Condition> conditions;
private Integer limit;
private Integer offset;

@Getter
@Setter
public class Condition{
private String key;
private EConstant.OPERATION operation;
private String value;
}
}
public Specification<T> getSpec(SearchCriteria.Condition condition){
....
}

最佳答案

如果我没理解错的话:

 IntStream.range(0, searchCriteria.getConditions().size())
.mapToObj(index-> getSpec(searchCriteria.getConditions().get(index)))
.reduce(Specification::and)
.orElseThrow(SomeException::new) // or any default from Specification...

或者更好:

 searchCriteria.getConditions()
.stream()
.map(this::getSpec)
.reduce(Specification::and)
.orElseThrow(SomeException::new)

关于java - 使用 java8 流的规范列表组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54305870/

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