我用Java8编写了以下代码
List<CategoryTranslation> categoriesTranslation = categoriesRepository.findByLanguageId(languageId);
List<CategoryDTO> categoryList = categoriesTranslation
.stream()
.map(x -> categoriesAdapter.category2DTO(x))
.collect(Collectors.toList());
这可以正常工作,但我需要像这样转换。
List<CategoryTranslation> categoriesTranslation = categoriesRepository.findByLanguageId(languageId);
List<CategoryDTO> categoryList = new ArrayList<CategoryDTO>();
for (CategoryTranslation categoryTranslation : categoriesTranslation) {
CategoryDTO categoryDTO = categoriesAdapter.category2DTO(categoryTranslation);
categoryDTO.setTotal(categoryRepository.countTotalArticlesByCategory(categoryDTO.getCategoryId(), languageId));
categoryList.add(categoryDTO);
}
我知道我可以使用适配器,但我不喜欢在Adapter中使用JPA。
发布于 2020-06-03 03:49:16
只需创建一个categorty2DTOWithTotal(CategoryTranslation ct, Long? languiageId)
方法。否则,您将不得不调用forEach
,但它是一个终止方法,因此您不能将其分组到列表中。从理论上讲,如果设置total会导致合理的映射,您可以引入一个方法来实现这一点,但在这里似乎有点牵强。
void aMethod(Long? languageId) {
List<CategoryTranslation> categoriesTranslation = categoriesRepository
.findByLanguageId(languageId);
List<CategoryDTO> categoryList = categoriesTranslation
.stream()
.map(x -> category2DTOWithTotal(x, languageId))
.collect(Collectors.toList());
}
CategoryDTO category2DTOWithTotal(CategoryTranslation ct, Long? languageId) {
CategoryDTO categoryDTO = categoriesAdapter.category2DTO(categoryTranslation);
categoryDTO.setTotal(
categoryRepository.countTotalArticlesByCategory(
categoryDTO.getCategoryId(), languageId
)
);
return categoryDTO;
}
或者,您可以稍后设置total:
void aMethod(Long? languageId) {
List<CategoryDTO> categoryList = categoriesTranslation
.stream()
.map(categoriesAdapter::category2DTO)
.collect(Collectors.toList());
categoryList.forEach(dto -> dto.setTotal(
categoryRepository.countTotalArticlesByCategory(
categoryDTO.getCategoryId(), languageId
)
);
}
为了完整起见,我们提供了一个可映射版本的setting total:
void aMethod(Long? languageId) {
List<CategoryTranslation> categoriesTranslation = categoriesRepository
.findByLanguageId(languageId);
List<CategoryDTO> categoryList = categoriesTranslation
.stream()
.map(categoriesAdapter::category2DTO)
.map(x -> setTotal(x, languageId))
.collect(Collectors.toList());
}
CategoryDTO setTotal(CategoryDTO ctd, Long? languageId) {
ctd.setTotal(
categoryRepository.countTotalArticlesByCategory(ctd.getCategoryId(), languageId)
);
return ctd;
}
https://stackoverflow.com/questions/62159270
复制相似问题