我想使用Streams.intRange(int start,int end,int step)实现反向排序的流。但是,似乎java.util.Streams类不再可用(但是它仍在标准库的rt.jar中)。此方法是在其他类中还是被其他方法替代?
实际上,JDK中再也没有这种方法了。您能获得的下一个最接近的位置是,IntStream.range()但是只会一步一步走。
IntStream.range()
一种解决方案是实施您自己的解决方案Spliterator.OfInt。例如这样的东西(很粗;可以改进!):
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()上面的类的实例生成流。
StreamSupport.intStream()