有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    只需创建一个方法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;
    }
    

    或者,您可以稍后设置总计:

    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;
    }