java - Java 流:从 Pair 到 Flat配对
问题描述
我需要平流Pair<Application, FileObject[]>
,到流Pair<Application, FileObject>
。
目前,我已经编码:
List<Application> applications = this.applicationDao.findAll();
applications.stream()
.map(app ->
new Pair<Application, FileObject[]>(
app,
this.massiveInterfaceService.getPendingDocuments(app)
)
);
所以,我需要的是获得一个Pair<app, FileObject>
.
this.massiveInterfaceService.getPendingDocuments
是:
public Stream<FileObject> getPendingDocuments(Application app) { /*...*/ }
有任何想法吗?
解决方案
假设massiveInterfaceService.getPendingDocuments()
返回FileObject[]
,您可以创建如下方法:
Stream<Pair<Application, FileObject>> flatten(Pair<Application, FileObject[]> pair) {
return Arrays.stream(pair.getRight())
.map(fileObject -> new Pair.of(pair.getLeft(), fileObject));
}
然后在您的流中使用它:
Stream<Pair<Application, FileObject>> stream =
applications.stream()
.map(app ->
Pair.of(app, this.massiveInterfaceService.getPendingDocuments(app)))
.flatMap(this::flatten);
如果另一方面massiveInterfaceService.getPendingDocuments()
返回一个Stream<FileObject>
Stream<Pair<Application, FileObject>> stream =
applications.stream()
.flatMap(app ->
this.massiveInterfaceService
.getPendingDocuments(app)))
.map(fileObject -> Pair.of(app, fileObject)));
从你的问题中不清楚哪个是正确的。
推荐阅读
- python - 如何使用 pytest 在 paramiko SSHClient() 中模拟“连接”
- mule - Mule 无法作为窗口服务启动
- visual-studio-code - VSCode:更改打印颜色()
- git - 如何在 git 中回滚并重新开始(保留历史记录和两者之间的合并)
- flutter - Flutter Reworked 问题:问题在带有按钮的小部件和带有倒数计时器的小部件之间共享状态
- php - 如何在奏鸣曲编辑表单中显示字段值?
- arrays - SwiftUI: List, ForEach, indices and .onDelete not working when using TextField() - (Index out of range)
- javascript - Rewrite condition to use only one console.log
- html - 移动响应
- azure - Request origin http://localhost:19006 does not have permission to access the resource