如果是多级类别存储在一个表中,通常采用数据库链表,xml再进行映射。现在,用流处理就可解决。
示例代码:
@Autowired
private CategoryService categoryService;
@Test
public void test1(){
//查所有类别数据
List<Category> categories=categoryService.list();
//过滤一级类别
List<Category> collect = categories.stream().filter(item ->{
return item.getParentId() == 0;
//重新映射夫类别拥有的子类别 递归实现
}).map(map -> {
map.setCates(getSons(categories, map));
return map;
}).collect(Collectors.toList());
System.out.println(collect);
}
private List<Category> getSons(List<Category> categories, Category map) {
List<Category> collect = categories.stream().filter(item -> {
//过滤出子类别
return item.getParentId() == map.getId();
}).map(map2 -> {
map2.setCates(getSons(categories, map2));
//将子类别赋值给夫类别
return map2;
}).collect(Collectors.toList());
return collect;
}