将所有类别的所有列表拆分为子类别((仅限java)

yruzcnhs  于 2021-07-04  发布在  Java
关注(0)|答案(2)|浏览(254)

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

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

如何转换为DTO列表,如下所示:

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

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

jutyujz0

jutyujz01#

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());
    }
}
yacmzcpb

yacmzcpb2#

创建 Map<Long, CategoryDTO> 然后从 categoryList ,Map idCategoryDTOCategory 对象。
然后循环通过 categoryList 再次,查找两者 id 以及 parentId 在Map上,添加到 subcategories 适当列出。
e、 g.类似这样:

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

相关问题