How to create an infinite Stream out of an Iterator?

前端 未结 4 1679
甜味超标
甜味超标 2020-12-09 03:14

Looking at the following class I\'ve made:

public class FibonacciSupplier implements Iterator {
    private final IntPredicate hasNextPredicat         


        
4条回答
  •  情歌与酒
    2020-12-09 04:01

    Your mistake is to think that you need an Iterator or a Collection to create a Stream. For creating an infinite stream, a single method providing one value after another is enough. So for your class FibonacciSupplier the simplest use is:

    IntStream s=IntStream.generate(FibonacciSupplier.infinite()::next);
    

    or, if you prefer boxed values:

    Stream s=Stream.generate(FibonacciSupplier.infinite()::next);
    

    Note that in this case the method does not have to be named next nor fulfill the Iterator interface. But it doesn’t matter if it does as with your class. Further, as we just told the stream to use the next method as a Supplier, the hasNext method will never be called. It’s just infinite.

    Creating a finite stream using your Iterator is a bit more complicated:

    Stream s=StreamSupport.stream(
      Spliterators.spliteratorUnknownSize(
        FibonacciSupplier.finite(intPredicate), Spliterator.ORDERED),
      false);
    

    In this case if you want a finite IntStream with unboxed int values your FibonacciSupplier should implement PrimitiveIterator.OfInt.

提交回复
热议问题