使用stream流遍历树型菜单

1.首先传统方式是使用递归遍历树型菜单,可以这么理解就是先获取跟节点然后在获取子节点。

编写实体类

@Data
@Builder
public class mout {
    private Integer id;
    private String name;
    private Integer parentId;
    private List<mout> childList;
    public mout(Integer id,String name,Integer parentId){
        this.id=id;
        this.name=name;
        this.parentId=parentId;
    }
    public mout(Integer id,String name,Integer parentId,List<mout> childList){
        this.id=id;
        this.name=name;
        this.parentId=parentId;
        this.childList=childList;
    }
}
@Test
public void tetxt1() {
//模拟数据库查询数据
    final List<mout> moutList = Arrays.asList(
            new mout(1, "跟节点", 0)
            ,new mout(2,"更节点子的节点1",1),
            new mout(3,"子节点1-1",1),
            new mout(4,"子节点1-2",2),
            new mout(5,"子节点2",2),
            new mout(6,"子节点2-1",3));
//遍历获取跟节点,并且添加子节点
    final List<mout> collect = moutList.stream().filter(m -> m.getParentId() == 0).map((m) -> {
        m.setChildList(getchildList(m, moutList));
        return m;
    }).collect(Collectors.toList());

    final Object o = JSON.toJSON(collect);
    System.out.println(o);
}
//获取子节点
@Test
    public List<mout> getchildList(mout mout,List<mout> moutList){
    final List<com.baidu.entity.mout> collect = moutList.stream().filter(mout1 -> {
        return Objects.equals(mout1.getParentId(), mout.getId());
    }).map(mout1 -> {
                mout1.setChildList(getchildList(mout1, moutList));
                return mout1;
            }
    ).collect(Collectors.toList());
    return collect;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

把柄

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值