如何使用 Java 8 创建无限流

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22483554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:00:44  来源:igfitidea点击:

How to create an infinite stream with Java 8

javajava-8

提问by sndyuk

Is there a easy way to create a infinity stream using java-8without external libraries?

有没有一种简单的方法可以在没有外部库的情况下使用java-8创建无限流?

For example in Scala:

例如在 Scala 中:

Iterator.iterate(0)(_ + 2)

采纳答案by skiwi

Yes, there is an easyway:

是的,有一个简单的方法:

IntStream.iterate(0, i -> i + 2);

With as usecase:

作为用例:

IntStream.iterate(0, i -> i + 2)
         .limit(100)
         .forEach(System.out::println);

Which prints out 0 to 198 increasing in steps of 2.

它打印出 0 到 198,以 2 的步长递增。

The generic method is:

通用方法是:

Stream.iterate(T seed, UnaryOperator<T> f);

The latter may be more uncommon in usage.

后者在使用中可能更不常见。

回答by Jesper

Here is an example:

下面是一个例子:

PrimitiveIterator.OfInt it = new PrimitiveIterator.OfInt() {
    private int value = 0;

    @Override
    public int nextInt() {
        return value++;
    }

    @Override
    public boolean hasNext() {
        return true;
    }
};

Spliterator.OfInt spliterator = Spliterators.spliteratorUnknownSize(it,
    Spliterator.DISTINCT | Spliterator.IMMUTABLE |
    Spliterator.ORDERED | Spliterator.SORTED);

IntStream stream = StreamSupport.intStream(spliterator, false);

It's a bit verbose, as you see. To print the first 10 elements of this stream:

如您所见,这有点冗长。要打印此流的前 10 个元素:

stream.limit(10).forEach(System.out::println);

You can ofcourse also transform the elements, like you do in your Scala example:

您当然也可以转换元素,就像您在 Scala 示例中所做的那样:

IntStream plusTwoStream = stream.map(n -> n + 2);

Note that there are built-in infinite streams such as java.util.Random.ints()which gives you an infinite stream of random integers.

请注意,有内置的无限流,例如java.util.Random.ints()它为您提供无限的随机整数流。

回答by Bassem Reda Zohdy

You can build your own InfiniteStream by implementing stream and consumer and compose both and may will need queue to queueing your data as :

您可以通过实现流和消费者来构建自己的 InfiniteStream 并组合两者,并且可能需要队列将您的数据排队为:

public class InfiniteStream<T> implements Consumer<T>, Stream<T> {
private final Stream<T> stream;
private final Queueing q;
...
public InfiniteStream(int length) {
    this.q = new Queueing(this.length);
    this.stream = Stream.generate(q);
    ...
}
    //implement stream methods
    //implement accept
}

check full code here https://gist.github.com/bassemZohdy/e5fdd56de44cea3cd8ff

在此处查看完整代码 https://gist.github.com/bassemZohdy/e5fdd56de44cea3cd8ff

回答by Oleksandr Pyrohov

There is another possible solution in Java 8:

Java 8 中有另一种可能的解决方案:

AtomicInteger adder = new AtomicInteger();
IntStream stream = IntStream.generate(() -> adder.getAndAdd(2));

Important: an order of numbers is preserved only if the stream is sequential.

重要提示:仅当流是顺序的时才会保留数字顺序。



It's also worth noting that a new version of the IntStream.iteratehas been added since Java 9:

还值得注意的是,IntStream.iterateJava 9以来已添加了新版本:

static IntStream iterate?(int seed,
                         IntPredicate hasNext,
                         IntUnaryOperator next);
  • seed -the initial element;
  • hasNext -a predicate to apply to elements to determine when the stream must terminate;
  • next -a function to be applied to the previous element to produce a new element.
  • 种子 -初始元素;
  • hasNext -应用于元素以确定流何时必须终止的谓词;
  • next -应用于前一个元素以生成新元素的函数。

Examples:

例子:

IntStream stream = IntStream.iterate(0, i -> i >= 0, i -> i + 2);

IntStream.iterate(0, i -> i < 10, i -> i + 2).forEach(System.out::println);