递归如何在Java 8 Stream中工作? [英] How does recursion work in a Java 8 Stream?
问题描述
我有一个这样的方法,我正在使用Streams的递归:
private static List< Member> convertToFlatList(List< Member> memberList)
{
return memberList.stream()。flatMap(i - > Stream.concat(Stream.of(i),convertToFlatList(i.getChildren())。流()))收集(Collectors.toList())。
}
让我们说会员
class有一个子成员列表,始终初始化为空列表。这里我正在做的是将成员的分层列表转换为平面列表。我明白那一部分。我不明白递归是如何工作的。
在递归中,当满足某些条件时终止递归。但在这里,我没有给出故意终止的任何条件。那么终止部分如何在这里工作?
递归将在 memberList $ c时结束$ c>将为空,因为在这种情况下将返回空的
列表
。
ie当 i.getChildren()
是一个空的 List
时,递归调用 convertToFlatList(i。 getChildren())
将收到一个空的列表
,因此 Stream
管道将不会进行另一个递归调用(因为它没有执行 flatMap
的元素),并将返回一个空的 List
。 / p>
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());
}
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
.
这篇关于递归如何在Java 8 Stream中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!