【问题标题】:Split all list of all categories into subcategories? (with Java only)将所有类别的所有列表拆分为子类别? (仅限 Java)
【发布时间】:2020-09-05 19:56:47
【问题描述】:

我们有一个实体类和所有类别的列表:

class Category {
  Long id, parentId;
}
...
List<Category> categoryList = <...>;

如何转换成这样的 DTO 列表:

class CategoryDTO {
  Long id; 
  List<CategoryDTO> subcategories;
}

如果没有一对一的实体关系,如何做到这一点?

【问题讨论】:

  • 基于Category 类。可以有没有父对象的对象吗?如果是,你如何标记它?如果不是,那是否意味着它们之间存在一个循环?
  • 显然可以多级吧?
  • 可以有无限个级别。主要级别有 parentId = null

标签: java oop jpa collections dto


【解决方案1】:
public class CategoryConverterImpl implements CategoryConverter {
    private CategoryDTO convertEntity(Category s) {
        Long id = s.getId();
        return new CategoryDTO()
                .setId(id)
                .setSubcategories(
                        convertCollection(
                                categoryCollection.stream()
                                        .filter(c -> Objects.equals(c.getParentCategoryId(), id))
                                        .collect(Collectors.toList())
                        )
                );
    }

    private List<CategoryDTO> convertCollection(Collection<Category> categoryCollection) {
        return categoryCollection.stream()
                .map(this::convertEntity)
                .collect(Collectors.toList());
    }

    private Collection<Category> categoryCollection;

    @Override
    public List<CategoryDTO> convert(Collection<Category> categoryCollection) {
        this.categoryCollection = categoryCollection;
        return categoryCollection.stream()
                .filter(c -> c.getParentCategoryId() == null)
                .map(this::convertEntity)
                .collect(Collectors.toList());
    }
}

【讨论】:

    【解决方案2】:

    创建一个Map&lt;Long, CategoryDTO&gt; 并将其从categoryList 填充,将id 映射到从Category 对象创建的CategoryDTO

    然后再次循环遍历categoryList,在地图中同时查找idparentId,并根据需要添加到subcategories 列表中。

    例如像这样:

    Map<Long, CategoryDTO> categoryDTOs = new LinkedHashMap<>();
    for (Category category : categoryList) {
        categoryDTOs.put(category.getId(), new CategoryDTO(category.getId()));
    }
    for (Category category : categoryList) {
        if (category.getParentId() != null) {
            categoryDTOs.get(category.getParentId())
                        .addSubcategory(categoryDTOs.get(category.getId()));
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-05
      • 1970-01-01
      • 1970-01-01
      • 2015-07-02
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多