Java 8超级类流,父文件,组件父项,链表等 [英] Java 8 Stream of Super Classes, Parent Files, Component Parents, linked list, etc
问题描述
我想将以下 for
语句转换为Java 8流(即 Stream< Class<?>>
)。理想的解决方案很简单,我可以很容易地适应各种遍历链表的情况(例如 File.getParentFile()
, Component.getParent()
)。
I would like to convert the following for
statement to a Java 8 stream (i.e. Stream<Class<?>>
). The ideal solution would be simple enough that I can easily adapt it for a variety of situations of traversing a linked list (e.g. File.getParentFile()
, Component.getParent()
).
Class<?> clazz;
Object value;
value = ...;
for (clazz = value.getClass(); clazz != null; clazz = clazz.getSuperclass())
...
我意识到创建流的几行代码不会比单个更简单
声明。但是,一个流使的主体
循环更简单,因此需要一个流。
I realize that a few lines of code to create a stream isn't going to be simpler than a single for
statement. However, a stream makes the body of the for
loop simpler and hence a stream is desirable.
推荐答案
你需要一个 takeWhile
方法,该方法仅出现在JDK-9中。目前,您可以使用可用的后端口,例如,在我的 StreamEx 库中:
Stream<Class<?>> stream = StreamEx.iterate(value.getClass(), Class::getSuperClass)
.takeWhile(Objects::nonNull);
在JDK-9中,只需将 StreamEx
替换为 Stream
。
In JDK-9 just replace StreamEx
with Stream
.
这篇关于Java 8超级类流,父文件,组件父项,链表等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!