How do streams stop?

前端 未结 2 624
星月不相逢
星月不相逢 2020-12-06 02:33

I was wondering when I created my own infinite stream with Stream.generate how the Streams which are in the standard library stop...

For example when yo

2条回答
  •  悲哀的现实
    2020-12-06 03:16

    I have created a generic workaround for this

    public class GuardedSpliterator implements Spliterator {
    
      final Supplier generator;
    
      final Predicate termination;
    
      final boolean inclusive;
    
      public GuardedSpliterator(Supplier generator, Predicate termination, boolean inclusive) {
        this.generator = generator;
        this.termination = termination;
        this.inclusive = inclusive;
      }
    
      @Override
      public boolean tryAdvance(Consumer action) {
        T next = generator.get(); 
        boolean end = termination.test(next);
        if (inclusive || !end) {
          action.accept(next);
        }
        return !end;
      }
    
      @Override
      public Spliterator trySplit() {
        throw new UnsupportedOperationException("Not supported yet.");
      }
    
      @Override
      public long estimateSize() {
        throw new UnsupportedOperationException("Not supported yet.");
      }
    
      @Override
      public int characteristics() {
        return Spliterator.ORDERED;
      }
    
    }
    

    Usage is pretty easy:

    GuardedSpliterator source = new GuardedSpliterator<>(
        ()  -> rnd.nextInt(),
        (i) -> i > 10,
        true
    );
    
    Stream ints = StreamSupport.stream(source, false);
    
    ints.forEach(i -> System.out.println(i));    
    

提交回复
热议问题