不幸的是,Stream API并不是非常适合解决涉及Stream元素的依赖操作的问题,例如此元素。
但是,您可以为此使用StreamEx库:
public static void main(String[] args) { IntStream seq = IntStream.of(1, 2, 3, -1, -1, 1, 2, 1, 2); IntUnaryOperator next = i -> i + 1; List<List<Integer>> result = IntStreamEx.of(seq).boxed().groupRuns((i1, i2) -> next.applyAsInt(i1) == i2).toList(); System.out.println(result); // prints "[[1, 2, 3], [-1], [-1], [1, 2], [1, 2]]"}这将分组为
List所有连续的整数,其中第二个等于
next应用于第一个的函数。最后,将此流收集到中
List。



