话不多说,上代码
1.创建实体类
@Data
public class MallProductTypeInfo
{
/** ID */
private Long id;
/** 类型名称 */
private String typeName;
/** 类型名称id */
private Long parentId;
/** 子分类 */
private List<MallProductTypeInfo> children;
}
2.stream流处理数据
//stream流处理数据
List<MallProductTypeInfo> typeInfos = typeInfoList.stream().filter((mallProductType)->
//条件
mallProductType.getParentId()==0
).peek((menu)->
menu.setChildren(getChildren(menu,typeInfoList))
).sorted(
Comparator.comparing(MallProductTypeInfo::getId)
).collect(Collectors.toList());
return typeInfos;
3.在创建一个方法,递归查找所有菜单的子菜单
/**
* 递归查找所有菜单的子菜单
* @param root
* @param all
* @return
*/
private List<MallProductTypeInfo> getChildren(MallProductTypeInfo root, List<MallProductTypeInfo> all) {
List<MallProductTypeInfo> children = all.stream().filter((newRetailProductType ->
newRetailProductType.getParentId().equals(root.getId()))
).peek((newRetailProductType ->
newRetailProductType.setChildren(getChildren(newRetailProductType, all)))
).sorted(
Comparator.comparing(MallProductTypeInfo::getId)
).collect(Collectors.toList());
if (children.size()==0 || children==null){
return null;
}
return children;
}
完成!!!