Java 8 Stream of superclasses, parent files, component parents, linked list, etc.

I would like to convert the following statement forto a Java 8 stream (i.e. Stream<Class<?>>). The ideal solution would be simple enough so that I can easily adapt it for different situations the passage of the linked list (for example File.getParentFile(), Component.getParent()).

  Class<?> clazz;
  Object value;

  value = ...;

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

I understand that a few lines of code to create a stream will not be easier than a simple statement for. However, flow makes the body of the cycle forsimpler and, therefore, flow is desirable.

+4
source share
2 answers

takeWhile, JDK-9. , , , StreamEx:

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

JDK-9 StreamEx Stream.

+6

, , 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);
   }
}
0

Source: https://habr.com/ru/post/1625574/


All Articles