java8实现树形三级分类
时间: 2023-05-21 18:00:56 浏览: 152
可以使用递归算法实现树形三级分类,具体实现可以参考以下代码:
```
public class Category {
private Long id;
private String name;
private Long parentId;
private List<Category> children;
// getter and setter methods
// add child category
public void addChild(Category category) {
if (children == null) {
children = new ArrayList<>();
}
children.add(category);
}
// build category tree
public static List<Category> buildTree(List<Category> categories) {
Map<Long, Category> map = new HashMap<>();
List<Category> roots = new ArrayList<>();
for (Category category : categories) {
map.put(category.getId(), category);
}
for (Category category : categories) {
Long parentId = category.getParentId();
if (parentId == null || parentId == 0) {
roots.add(category);
} else {
Category parent = map.get(parentId);
if (parent != null) {
parent.addChild(category);
}
}
}
return roots;
}
}
```
使用示例:
```
List<Category> categories = new ArrayList<>();
categories.add(new Category(1L, "电子产品", null));
categories.add(new Category(2L, "手机", 1L));
categories.add(new Category(3L, "电脑", 1L));
categories.add(new Category(4L, "笔记本电脑", 3L));
categories.add(new Category(5L, "平板电脑", 3L));
categories.add(new Category(6L, "家具", null));
categories.add(new Category(7L, "沙发", 6L));
categories.add(new Category(8L, "床", 6L));
List<Category> tree = Category.buildTree(categories);
```