java8递归树形结构

递归菜单、栏目等

实体类

/**
 * id
 */
public Integer id;
/**
 * 名称
 */
public String name;
/**
 * 父id ,根节点为0
 */
public Integer parentId;
/**
 * 子节点信息
 */
public List<Menu> childList;


public Menu(Integer id, String name, Integer parentId) {
    this.id = id;
    this.name = name;
    this.parentId = parentId;
}

测试类

@Test
public void test1(){
    //模拟从数据源查询出来


    //获取父节点
    List<Menu> collect = menus.stream().filter(m -> m.getParentId() == 0).map(
            (m) -> {
                m.setChildList(getChildrens(m, menus));
                return m;
            }
    ).collect(Collectors.toList());
    System.out.println(JSON.toJSON(collect));

}
/**
 * 递归查询子节点
 * @param root  根节点
 * @param all   所有节点
 * @return 根节点信息
 */
private List<Menu> getChildrens(Menu root, List<Menu> all) {
    List<Menu> children = all.stream().filter(m -> {
        return Objects.equals(m.getParentId(), root.getId());
    }).map(
            (m) -> {
                m.setChildList(getChildrens(m, all));
                return m;
            }
    ).collect(Collectors.toList());
    return children;
}

执行test1测试类返回值(返回json格式,可以用json在线工具处理下)

[{"name":"手机","childList":[{"name":"苹果","childList":[{"name":"苹果-黑色","childList":[],"id":3,"parentId":2},{"name":"苹果-蓝色","childList":[],"id":4,"parentId":2}],"id":2,"parentId":1},{"name":"华为","childList":[{"name":"华为-黑色","childList":[],"id":6,"parentId":5},{"name":"华为-红色","childList":[{"name":"华为-红色-8+256","childList":[],"id":8,"parentId":7}],"id":7,"parentId":5}],"id":5,"parentId":1}],"id":1,"parentId":0},{"name":"水果","childList":[{"name":"香蕉","childList":[],"id":10,"parentId":9}],"id":9,"parentId":0}]

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值