慕斯王
这里的基本操作称为“压缩”:给定两个流As 和Bs 以及一个组合运算符(A, B) -> C,您可以创建一个 s 流C(截断为较短的输入流)。假设你有这样的功能<A, B, C> Stream<C> zip (Stream<? extends A> as, Stream<? extends B> bs, BiFunction<? super A, ? super B, ? extends C> combine);您可以将您的操作实现为zip(ordered.stream(), ordered.stream().skip(1), this::isDifferent).anyMatch(x -> x);// ordered: a b c d ... y z// skipped: b c d ... y z// zipped : (a, b) (b, c) (c, d) ... (y, z)zip标准库中没有。如果您使用的是像 Guava 这样的东西,您可以检查它是否有这个操作,或者,您可以自己实现它并将其粘贴到某个实用程序类中,我将重现那里列出的代码(它似乎是从实际 Streams API 的测试版抄袭而来):public static<A, B, C> Stream<C> zip(Stream<? extends A> a, Stream<? extends B> b, BiFunction<? super A, ? super B, ? extends C> zipper) { Objects.requireNonNull(zipper); Spliterator<? extends A> aSpliterator = Objects.requireNonNull(a).spliterator(); Spliterator<? extends B> bSpliterator = Objects.requireNonNull(b).spliterator(); // Zipping looses DISTINCT and SORTED characteristics int characteristics = aSpliterator.characteristics() & bSpliterator.characteristics() & ~(Spliterator.DISTINCT | Spliterator.SORTED); long zipSize = ((characteristics & Spliterator.SIZED) != 0) ? Math.min(aSpliterator.getExactSizeIfKnown(), bSpliterator.getExactSizeIfKnown()) : -1; Iterator<A> aIterator = Spliterators.iterator(aSpliterator); Iterator<B> bIterator = Spliterators.iterator(bSpliterator); Iterator<C> cIterator = new Iterator<C>() { @Override public boolean hasNext() { return aIterator.hasNext() && bIterator.hasNext(); } @Override public C next() { return zipper.apply(aIterator.next(), bIterator.next()); } }; Spliterator<C> split = Spliterators.spliterator(cIterator, zipSize, characteristics); return (a.isParallel() || b.isParallel()) ? StreamSupport.stream(split, true) : StreamSupport.stream(split, false);}