此处使用 Java 22 预科语言
// [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22]
List<String> lines = IntStream.range(1, 22).mapToObj(Integer::toString).toList();
// [10,9,8,7,6,5,4,3,2,1,20,19,18,17,16,15,14,13,12,11,22,21]
List<String> output = list.stream()
.gather(Gatherers.windowFixed(10))
.flatMap(window -> window.reversed().stream())
.toList();
使用了新的>>>>。 https://download.java.net/java/early_access/jdk22/docs/api/java.base/java/util/stream/Gatherers.html#windowFixed(int) rel=“nofollow noreferer”>Gatherers.windowFixed
召集人将清单分成10个项目。
Walkthrough
- Convert the
List<String>
to a Stream<String>
.
// [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22]
lines.stream()
- Gather the elements into windows with 10 elements (or fewer, if at the end of the stream). This results in a
Stream<List<String>>
.
// [[1,2,3,4,5,6,7,8,9,10],[11,12,13,14,15,16,17,18,19,20],[21,22]]
.gather(Gatherers.windowFixed(10))
- Reverse each window, and then flatten it. This converts back to
Stream<String>
.
// [10,9,8,7,6,5,4,3,2,1,20,19,18,17,16,15,14,13,12,11,22,21]
.flatMap(window -> window.reversed().stream())
- Convert the
Stream<String>
to a List<String>
.
// [10,9,8,7,6,5,4,3,2,1,20,19,18,17,16,15,14,13,12,11,22,21]
.toList()
Javadocs
rel=“nofollow noreferer”>>:
An intermediate operation that transforms a stream of input elements into a stream of output elements, optionally applying a final action when the end of the upstream is reached. […]
[…]
收集业务有许多例子,包括但不限于:将各种要素归类为批量(缩小功能);重复连续复制类似内容;增量积累功能(固定扫描);增量重订功能等。 :提供共同收集业务的实施。
Stream.gather
<>::
回归包括将特定召集人应用到这一流要素的结果。
>: 密码>;Gatherers.windowFixed
• 返回一个把部件聚集到窗户的召集人——一组有固定规模的内容。 如果溪流空,就不会生产窗户。 最后一个窗口所含元素可能少于所提供的窗口规模。
例:
// will contain: [[1, 2, 3], [4, 5, 6], [7, 8]]
List<List<Integer>> windows =
Stream.of(1,2,3,4,5,6,7,8).gather(Gatherers.windowFixed(3)).toList();