配对,java,java-stream,apache-commons"/>

首页 > 解决方案 > 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) { /*...*/ }

有任何想法吗?

标签: javajava-streamapache-commons

解决方案


假设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)));

从你的问题中不清楚哪个是正确的。


推荐阅读