foreach jdk8 递归_递归如何在Java 8 Stream中工作?

这篇博客探讨了如何使用Java中的递归和Stream API将具有层级结构的成员列表转换为扁平化的列表。在给定的方法中,递归在遇到空列表时终止。当成员的子列表为空时,不再进行递归调用,返回空列表,从而结束递归流程。这种方法有效地展开并合并了整个成员树。
摘要由CSDN通过智能技术生成

I have a method like this where I'm using recursion with Streams:

private static List convertToFlatList(List memberList)

{

return memberList.stream().flatMap(i -> Stream.concat(Stream.of(i), convertToFlatList(i.getChildren()).stream())).collect(Collectors.toList());

}

Lets say a Member class has a children list of members that is always initialized to an empty list. Here what I'm doing is converting the hierarchical list of members to a flat list. I understand that part. What I don't understand is how recursion works here.

In recursion, it's terminated when certain conditions are met. But here I'm not giving any condition for terminating intentionally. So how does the termination part work here?

解决方案

The recursion will end when memberList will be empty, since at this case an empty List will be returned.

i.e. when i.getChildren() is an empty List, the recursive call convertToFlatList(i.getChildren()) will receive an empty List, so the Stream pipeline won't make another recursive call (since it has no elements to execute flatMap on), and will return an empty List.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值