我想从Java 8 Stream
中检索并删除下一项,而Stream
不会被关闭。
Stream<Integer> integerStream = Stream.iterate( 0, x -> new Integer(x + 1) );
Integer zero = integerStream.getNext(); // 0
Integer one = integerStream.getNext(); // 1
...
这可能吗?
答案 0 :(得分:14)
是的,有一种方法可以做到这一点,但有一些限制。
Stream<Integer> infiniteStream = Stream.iterate( 0, x -> new Integer(x + 1) );
Iterator<Integer> iter = infiniteStream.iterator();
Integer zero = iter.next();
Integer one = iter.next();
可替换地,
Stream<Integer> infiniteStream = Stream.iterate( 0, x -> new Integer(x + 1) );
Spliterator<Integer> spliterator = infiniteStream.spliterator();
spliterator.tryAdvance(i -> System.out.println(i)); // zero
spliterator.tryAdvance(i -> System.out.println(i)); // one
如果有Stream
,则可以从中获取Iterator
或Spliterator
,或查询它是否为并行流等。这些是在BaseStream
接口上定义,是Stream
的超接口,这使得它们容易错过。
在这种情况下,我们知道流是无限的,因此无需调用Iterator的hasNext()
方法或检查Spliterator tryAdvance()
的返回值
限制是iterator()
的{{1}}和spliterator()
方法都是终端操作,这意味着在他们被调用之后,返回Iterator或Spliterator可以独占访问Stream表示的值。不允许对流进行进一步操作(例如Stream
或filter
等),并且map
将会遇到这些操作。
如果您想剥离前几个元素,然后恢复流处理,可以将分裂器重新转换为如下所示的流:
IllegalStateException
这可能对某些事情很好,但我不确定我是否会推荐这种技术。我认为它会在生成下一个元素的路径中添加一些额外的对象,从而增加额外的方法调用。
编辑评论(与您的问题无关):
Stream<Integer> stream2 = StreamSupport.stream(spliterator, false);
。而是使用new Integer(val)
,如果它可用,它将重复使用盒装整数,对于-128到127范围内的值通常是正确的。Integer.valueOf(val)
代替IntStream
,这样可以完全避免装箱费用。它没有完整的流操作,但它有Stream<Integer>
,它采用一个对原始iterate()
值进行操作的函数。答案 1 :(得分:1)
基于Stuart's answer和Iterator-to-Stream conversion,我提出了以下快速而肮脏的包装类。它未经过测试,并且不是线程安全的,但它为我提供了我目前所需的内容 - 删除和使用单个项目,同时保留此流&#34;打开& #34 ;.
PeelingStream<T>
提供了一种方法T getNext()
,可以屏蔽someWrappedStream.iterator()
终端流操作语义:
public class PeelingStream<T> implements Stream<T> {
private Stream<T> wrapped;
public PeelingStream(Stream<T> toBeWrapped) {
this.wrapped = toBeWrapped;
}
public T getNext() {
Iterator<T> iterator = wrapped.iterator();
T next = iterator.next();
Iterable<T> remainingIterable = () -> iterator;
wrapped = StreamSupport.stream(remainingIterable.spliterator(),
false);
return next;
}
///////////////////// from here, only plain delegate methods
public Iterator<T> iterator() {
return wrapped.iterator();
}
public Spliterator<T> spliterator() {
return wrapped.spliterator();
}
public boolean isParallel() {
return wrapped.isParallel();
}
public Stream<T> sequential() {
return wrapped.sequential();
}
public Stream<T> parallel() {
return wrapped.parallel();
}
public Stream<T> unordered() {
return wrapped.unordered();
}
public Stream<T> onClose(Runnable closeHandler) {
return wrapped.onClose(closeHandler);
}
public void close() {
wrapped.close();
}
public Stream<T> filter(Predicate<? super T> predicate) {
return wrapped.filter(predicate);
}
public <R> Stream<R> map(Function<? super T, ? extends R> mapper) {
return wrapped.map(mapper);
}
public IntStream mapToInt(ToIntFunction<? super T> mapper) {
return wrapped.mapToInt(mapper);
}
public LongStream mapToLong(ToLongFunction<? super T> mapper) {
return wrapped.mapToLong(mapper);
}
public DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper) {
return wrapped.mapToDouble(mapper);
}
public <R> Stream<R> flatMap(
Function<? super T, ? extends Stream<? extends R>> mapper) {
return wrapped.flatMap(mapper);
}
public IntStream flatMapToInt(
Function<? super T, ? extends IntStream> mapper) {
return wrapped.flatMapToInt(mapper);
}
public LongStream flatMapToLong(
Function<? super T, ? extends LongStream> mapper) {
return wrapped.flatMapToLong(mapper);
}
public DoubleStream flatMapToDouble(
Function<? super T, ? extends DoubleStream> mapper) {
return wrapped.flatMapToDouble(mapper);
}
public Stream<T> distinct() {
return wrapped.distinct();
}
public Stream<T> sorted() {
return wrapped.sorted();
}
public Stream<T> sorted(Comparator<? super T> comparator) {
return wrapped.sorted(comparator);
}
public Stream<T> peek(Consumer<? super T> action) {
return wrapped.peek(action);
}
public Stream<T> limit(long maxSize) {
return wrapped.limit(maxSize);
}
public Stream<T> skip(long n) {
return wrapped.skip(n);
}
public void forEach(Consumer<? super T> action) {
wrapped.forEach(action);
}
public void forEachOrdered(Consumer<? super T> action) {
wrapped.forEachOrdered(action);
}
public Object[] toArray() {
return wrapped.toArray();
}
public <A> A[] toArray(IntFunction<A[]> generator) {
return wrapped.toArray(generator);
}
public T reduce(T identity, BinaryOperator<T> accumulator) {
return wrapped.reduce(identity, accumulator);
}
public Optional<T> reduce(BinaryOperator<T> accumulator) {
return wrapped.reduce(accumulator);
}
public <U> U reduce(U identity,
BiFunction<U, ? super T, U> accumulator,
BinaryOperator<U> combiner) {
return wrapped.reduce(identity, accumulator, combiner);
}
public <R> R collect(Supplier<R> supplier,
BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner) {
return wrapped.collect(supplier, accumulator, combiner);
}
public <R, A> R collect(Collector<? super T, A, R> collector) {
return wrapped.collect(collector);
}
public Optional<T> min(Comparator<? super T> comparator) {
return wrapped.min(comparator);
}
public Optional<T> max(Comparator<? super T> comparator) {
return wrapped.max(comparator);
}
public long count() {
return wrapped.count();
}
public boolean anyMatch(Predicate<? super T> predicate) {
return wrapped.anyMatch(predicate);
}
public boolean allMatch(Predicate<? super T> predicate) {
return wrapped.allMatch(predicate);
}
public boolean noneMatch(Predicate<? super T> predicate) {
return wrapped.noneMatch(predicate);
}
public Optional<T> findFirst() {
return wrapped.findFirst();
}
public Optional<T> findAny() {
return wrapped.findAny();
}
}
小测试:
@Test
public void testPeelingOffItemsFromStream() {
Stream<Integer> infiniteStream = Stream.iterate(0, x -> x + 1);
PeelingStream<Integer> peelingInfiniteStream = new PeelingStream<>(infiniteStream);
Integer one = peelingInfiniteStream.getNext();
assertThat(one, equalTo(0));
Integer two = peelingInfiniteStream.getNext();
assertThat(two, equalTo(1));
Stream<Integer> limitedStream = peelingInfiniteStream.limit(3); // 2 3 4
int sumOf234 = limitedStream.mapToInt(x -> x.intValue()).sum();
assertThat(sumOf234, equalTo(2 + 3 + 4));
}
答案 2 :(得分:0)
我做了以下事情。原始流确实关闭了,但创建了一个与旧流完全相同的新流。
您将需要来自番石榴的 com.google.common.collect.Iterators。
import static com.google.common.collect.Iterators.concat;
import static com.google.common.collect.Iterators.singletonIterator;
import static java.util.Spliterators.spliteratorUnknownSize;
import static java.util.stream.StreamSupport.stream;
private <T> Stream<T> peekFirst(Stream<T> originalStream){
//This closes the original Stream
Iterator<T> originalIterator = originalStream.iterator();
if (!originalIterator.hasNext()) {
return Stream.of();
}
T firstElement = originalIterator.next();
doSomethingWithFirstElement(firstElement);
Iterator<T> newIterator = concat(
singletonIterator(firstElement),
originalIterator);
return stream(
spliteratorUnknownSize(newIterator, 0),
originalStream.isParallel());
}