如何在Java-8中合并来自同一关系的两个列表

问题描述

我下面有实体ManagerColleague

经理实体

@Entity
@Table(name = "Manager")
@Data
public class Manager implements java.io.Serializable {

    @Id
    @Column(name = "id")
    private Long id;
    
    @Column(name = "name")
    private String name;

    @OnetoMany
    @JoinColumn(name = "id")
    private List<Colleague> colleagues;
}

同事实体

@Entity
@Table(name = "Colleague")
@Data
public class Colleague implements java.io.Serializable {

    @Id
    @Column(name = "id")
    private Long id;

    @Column(name = "name")
    private String name;
}

以上关系可以在JSON中表示为

[
  {
    "id": "101","name": "manager1","colleagues": [
      {
        "id": "101","name": "colleague1"
      },{
        "id": "101","name": "colleague2"
      }
    ]
  },{
    "id": "101","name": "manager2","name": "colleague3"
      },"name": "colleague4"
      }
    ]
  }
]

我正在managerReposiotry.findAll()上检索结果为

List<Manager> managerList = managerReposiotry.findAll();

我想创建一个ManagerColleague中所有名称的超级列表

我目前正在做的是

List<String> names = new ArrayList<>();
managerList.stream()
           .forEach(manager -> {
                 List<String> nameList = 
                     manager.getColleagues().stream()
                                            .map(colleague -> colleague.getName())
                                            .collect(Collectors.toList());
                 names.addAll(nameList);
              }
           );

Java-8中还有其他方法可以改善上述代码吗?

谢谢!!

解决方法

您可以使用flatMap来平整Colleague的所有Manager,然后仅映射Colleague的名称并收集为列表。

List<String> names =
        managerList.stream()                                   // ...Stream<Manager>
                   .flatMap(m -> m.getColleagues().stream())   // ...Stream<Colleague>
                   .map(c-> c.getName())                       // ...Stream<String>
                   .collect(Collectors.toList());

但是,如果所有同事都有经理,则直接从数据库中获取更好的方法。

@Query("select c.name from Colleagues c")
List<String> findAllColleagueName();