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

前端 未结 2 1970
忘了有多久
忘了有多久 2021-01-18 15:29

I would like to convert the following for statement to a Java 8 stream (i.e. Stream>). The ideal solution would be simple eno

2条回答
  •  北恋
    北恋 (楼主)
    2021-01-18 16:17

    Here's the same code as presented in the question but implemented using a Spliterator. I am hoping someone can come up with a simpler, smarter answer.

      Class clazz;
      Object value;
    
      value = ...;
    
      >walkLinks(value.getClass(), Class::getSuperclass).
         ...
    
    
    public static  Stream walkLinks(T start, Function next)
    {
       WalkLinks walker;
       Stream result;
    
       walker = new WalkLinks<>(start, next);
       result = StreamSupport.stream(walker, false);
    
       return(result);
    }
    
    private static class WalkLinks extends Spliterators.AbstractSpliterator
    {
       private final Function m_next;
       private       T              m_value;
    
       public WalkLinks(T value, Function next)
       {
          super(Long.MAX_VALUE, Spliterator.ORDERED + Spliterator.NONNULL);
    
          m_value = value;
          m_next  = next;
       }
    
       @Override
       public boolean tryAdvance(Consumer action)
       {
          if (m_value == null)
             return(false);
    
          action.accept(m_value);
    
          m_value = m_next.apply(m_value);
    
          return(true);
       }
    }
    

提交回复
热议问题