Java 8个Stream of Super 类, Parent Files, Component Parents, linked list等

Java 8 Stream of Super Classes, Parent Files, Component Parents, linked list, etc

我想将以下 for 语句转换为 Java 8 流(即 Stream<Class<?>>)。理想的解决方案应该足够简单,以至于我可以轻松地适应遍历链表的各种情况(例如 File.getParentFile()Component.getParent())。

  Class<?> clazz;
  Object value;

  value = ...;

  for (clazz = value.getClass(); clazz != null; clazz = clazz.getSuperclass())
     ...

我意识到创建流的几行代码并不比单个 for 语句简单。但是,流使 for 循环的主体更简单,因此流是可取的。

这里的代码与问题中提供的代码相同,但使用 Spliterator 实现。我希望有人能想出一个更简单、更聪明的答案。

  Class<?> clazz;
  Object value;

  value = ...;

  <Class<?>>walkLinks(value.getClass(), Class::getSuperclass).
     ...


public static <T> Stream<T> walkLinks(T start, Function<T, T> next)
{
   WalkLinks<T> walker;
   Stream<T> result;

   walker = new WalkLinks<>(start, next);
   result = StreamSupport.stream(walker, false);

   return(result);
}

private static class WalkLinks<T> extends Spliterators.AbstractSpliterator<T>
{
   private final Function<T, T> m_next;
   private       T              m_value;

   public WalkLinks(T value, Function<T, T> next)
   {
      super(Long.MAX_VALUE, Spliterator.ORDERED + Spliterator.NONNULL);

      m_value = value;
      m_next  = next;
   }

   @Override
   public boolean tryAdvance(Consumer<? super T> action)
   {
      if (m_value == null)
         return(false);

      action.accept(m_value);

      m_value = m_next.apply(m_value);

      return(true);
   }
}

您需要一个 takeWhile method which will appear in JDK-9 only. Currently you can use a back-port which is available, for example, in my StreamEx 库:

Stream<Class<?>> stream = StreamEx.iterate(value.getClass(), Class::getSuperClass)
                                  .takeWhile(Objects::nonNull);

在 JDK-9 中只需将 StreamEx 替换为 Stream