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.
You need a
takeWhile
method which will appear in JDK-9 only. Currently you can use a back-port which is available, for example, in my StreamEx library:In JDK-9 just replace
StreamEx
withStream
.