实现说明
Stream Gatherers 批切与流式折叠的核心是类 BatchWindows和函数 main。
转换以 stream 管道组织——数据源、中间操作、终端收集器各自独立可读。
使用要点
- 每一步打印都带着自己的标签:
batches:、folded:。
常见问题
运行「Stream Gatherers 批切与流式折叠」会打印什么?
运行文件本身,batches:、folded: 这些前缀各对应一段演示逻辑。
核心语句
List<List<String>> batches = ids.stream()
.gather(Gatherers.windowFixed(3))
.toList();
String joined = ids.stream()
.gather(Gatherers.fold(
() -> new StringBuilder(),
(sb, id) -> sb.append(id).append(',')))
.findFirst()
.orElse("");
代码示例
import java.util.List;
import java.util.stream.Gatherers;
public class BatchWindows {
public static void main(String[] args) {
List<String> ids = List.of("a", "b", "c", "d", "e", "f", "g");
// windowFixed:把流切成定长批次,尾部不足也保留
List<List<String>> batches = ids.stream()
.gather(Gatherers.windowFixed(3))
.toList();
System.out.println("batches: " + batches);
// fold:流式累积出单一汇总值,没有中间集合
String joined = ids.stream()
.gather(Gatherers.fold(
() -> new StringBuilder(),
(sb, id) -> sb.append(id).append(',')))
.findFirst()
.orElse("");
System.out.println("folded: " + joined);
}
}