[英]How to generalize methods using functional Java
Can we reduce code duplication with these methods with the new java functional paradigm?我们可以使用新的 java 功能范例来减少代码重复吗? I tried to pass the function as param.
我试图将 function 作为参数传递。 But one has Functional and the other BiFunctional.
但是一个具有功能性,另一个具有双功能性。 Unable to make it as from below code {1} & {2} are diff JPA queries with different num of method args.
无法从下面的代码 {1} 和 {2} 中实现它是具有不同方法参数数量的差异 JPA 查询。 I am honestly new to this and appreciate any help.
老实说,我对此很陌生,并感谢任何帮助。
public long byId(List<Long> ids) {
Pageable pageRequest = PageRequest.of(0, 10, Sort.Direction.ASC, "id");
Page<SomeDAO> currentPage = repository.findByIdIn(ids, pageRequest); // {1}
long totalRecords = 0;
while (!currentPage.isEmpty()) {
pageRequest = pageRequest.next();
totalRecords += currentPage.getContent().size();
// some BL
currentPage = repository.findByIdIn(ids, pageRequest); // {1}
}
return totalRecords;
}
public long all() {
Pageable pageRequest = PageRequest.of(0, 10, Sort.Direction.ASC, "id");
Page<SomeDAO> currentPage = repository.findAll(pageRequest); // {2}
long totalRecords = 0;
while (!currentPage.isEmpty()) {
pageRequest = pageRequest.next();
totalRecords += currentPage.getContent().size();
// some BL
currentPage = repository.findAll(pageRequest); // {2}
}
return totalRecords;
}
public long byId(List<Long> ids) {
return general(pageRequest -> repository.findByIdIn(ids, pageRequest));
}
public long all() {
return general(pageRequest -> repository.findAll(pageRequest));
}
public long general(Function<Pageable, Page<SomeDAO>> find) {
Pageable pageRequest = PageRequest.of(0, 10, Sort.Direction.ASC, "id");
Page<SomeDAO> currentPage = find.apply(pageRequest);
long totalRecords = 0;
while (!currentPage.isEmpty()) {
pageRequest = pageRequest.next();
totalRecords += currentPage.getContent().size();
// some BL
currentPage = find.apply(pageRequest);
}
return totalRecords;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.