我需要压缩 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)));
从你的问题中不清楚哪个是正确的。
关于Java Stream : Flat from Pair<K, Object[]> to Pair<K, Object>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53395437/