小编典典

是否可以使用Streams.intRange函数?

java

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


阅读 258

收藏
2020-11-23

共1个答案

小编典典

实际上,JDK中再也没有这种方法了。您能获得的下一个最接近的位置是,IntStream.range()但是只会一步一步走。

一种解决方案是实施您自己的解决方案Spliterator.OfInt。例如这样的东西(很粗;可以改进!):

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;
    }
}

然后,您将使用StreamSupport.intStream()上面的类的实例生成流。

2020-11-23