递归如何与Java 8 Stream一起使用? [英] How does recursion work with Java 8 Stream?

查看:388
本文介绍了递归如何与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 ),并返回一个空的List.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆