代码之家  ›  专栏  ›  技术社区  ›  GolamMazid Sajib

使用Java8流的规范组合列表

  •  4
  • GolamMazid Sajib  · 技术社区  · 6 年前

    如何将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){
    ....
    }
    
    1 回复  |  直到 6 年前
        1
  •  5
  •   Eugene    6 年前

    如果我理解正确:

     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)