List of specification combine using java8 stream

Golam Mazid sajib :

How to use Java8 stream for this code:

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)));
    }

Using Stream:

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

Related class && method:

@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){
....
}
Eugene :

If I understood correctly:

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

Or even better:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=92090&siteId=1