How does recursion work with Java 8 Stream?(递归如何与 Java 8 Stream 一起工作?)
问题描述
我有一个这样的方法,我在 Streams 中使用递归:
I have a method like this where I'm using recursion with Streams:
private static List<Member> convertToFlatList(List<Member> memberList)
{
return memberList.stream().flatMap(i -> Stream.concat(Stream.of(i), convertToFlatList(i.getChildren()).stream())).collect(Collectors.toList());
}
假设一个 Member
类有一个子成员列表,它总是初始化为一个空列表.在这里,我正在做的是将成员的分层列表转换为平面列表.我理解那部分.我不明白的是这里的递归是如何工作的.
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?
推荐答案
当 memberList
为空时,递归将结束,因为在这种情况下,一个空的 List
将是返回.
The recursion will end when memberList
will be empty, since at this case an empty List
will be returned.
即当 i.getChildren()
为空 List
时,递归调用 convertToFlatList(i.getChildren())
将收到一个空 List
,因此 Stream
管道不会进行另一个递归调用(因为它没有要执行 flatMap
的元素),并且将返回一个空的 列表
.
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
.
这篇关于递归如何与 Java 8 Stream 一起工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:递归如何与 Java 8 Stream 一起工作?
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 转换 ldap 日期 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 获取数字的最后一位 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01