Reputation: 335
I have the following code in Java 8
List<CategoryTranslation> categoriesTranslation = categoriesRepository.findByLanguageId(languageId);
List<CategoryDTO> categoryList = categoriesTranslation
.stream()
.map(x -> categoriesAdapter.category2DTO(x))
.collect(Collectors.toList());
This works correctly , but I need to convert like this.
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);
}
I know that I could use the adapter but I don't like to use a JPA in Adapter.
Upvotes: 1
Views: 68
Reputation: 1687
Just create a method categorty2DTOWithTotal(CategoryTranslation ct, Long? languiageId)
.
Otherwise you'd have to call forEach
, but it's a terminating method so you couldn't group it into a list. In theory if setting total would result in sensible mapping, you could introduce a method which does that, but here it seems like a bit of a stretch.
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;
}
Or, you could set total later:
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
)
);
}
And for completeness, a mappable version of 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;
}
Upvotes: 1