java 8上的spring迭代值
我在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);
}
我知道我可以使用适配器,但我不喜欢在适配器中使用JPA
# 1 楼答案
只需创建一个方法
categorty2DTOWithTotal(CategoryTranslation ct, Long? languiageId)
。 否则,您必须调用forEach
,但它是一个终止方法,因此您无法将其分组到列表中。从理论上讲,如果设置total会产生合理的映射,您可以引入一种方法来实现这一点,但在这里似乎有点牵强或者,您可以稍后设置总计:
为完整起见,可映射版本的setting total: