是否可以使用Streams

是否可以使用Streams

本文介绍了是否可以使用Streams.intRange函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Streams.intRange(int start,int end,int step)来实现反向排序流。但是,似乎java.util.Streams类不再可用(但它仍然在标准库中的rt.jar中)。这个方法是在其他类中还是用其他类替换?

I wanted to use Streams.intRange(int start, int end, int step) to achieve reverse ordered stream. However it seems that java.util.Streams class is no longer available (however it is still in rt.jar in standard library). Is this method in some other class or replaced with something else?

推荐答案

在JDK中确实没有这样的方法;你可以得到的下一个最近的是 IntStream.range(),但这只会逐步执行。

There is indeed no such method anymore in the JDK; the next closest you could get is IntStream.range() but that will only step one by one.

一个这里的解决方案是实现你自己的 Spliterator.OfInt ;例如这样的东西(非常粗糙;可以改进!):

One solution here would be to implement your own Spliterator.OfInt; for instance something like this (VERY CRUDE; can be improved!):

public final class StepRange
    implements Spliterator.OfInt
{
    private final int start;
    private final int end;
    private final int step;

    private int currentValue;

    public StepRange(final int start, final int end, final int step)
    {
        this.start = start;
        this.end = end;
        this.step = step;
        currentValue = start;
    }

    @Override
    public OfInt trySplit()
    {
        return null;
    }

    @Override
    public long estimateSize()
    {
        return Long.MAX_VALUE;
    }

    @Override
    public int characteristics()
    {
        return Spliterator.IMMUTABLE | Spliterator.DISTINCT;
    }

    @Override
    public boolean tryAdvance(final IntConsumer action)
    {
        final int nextValue = currentValue + step;
        if (nextValue > end)
            return false;
        action.accept(currentValue);
        currentValue = nextValue;
        return true;
    }
}

然后你会使用从上面的类实例生成流。

You would then use StreamSupport.intStream() to generate your stream from an instance of the class above.

这篇关于是否可以使用Streams.intRange函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 20:25