它也不漂亮,但你可以用收藏家来做。我使用了内部带有数组的 ArrayList,但如果需要,您可以使用不同的中间集合类型。
我在这里所做的是一个收集器,它将每个项目添加为添加到累加器的最后一个数组上的第二个项目,并将其作为将添加到累加器的新数组上的第一个项目。
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
ArrayList<Integer[]> pairs =
stream.collect(
() -> new ArrayList<>(),
(acc, next) -> {
if(acc.isEmpty()) {
acc.add(new Integer[] {next, null});
} else {
acc.get(acc.size() - 1)[1] = next;
acc.add(new Integer[] {next, null});
}
},
ArrayList::addAll
);
pairs.forEach(a -> System.out.println(a[0] + ", " + a[1]));
//-> 1, 2
//-> 2, 3
//-> 3, 4
//-> 4, 5
//-> 5, 6
//-> 6, null