问题描述
我下面有实体Manager
和Colleague
经理实体
@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();
我想创建一个Manager
和Colleague
中所有名称的超级列表
我目前正在做的是
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);
}
);
谢谢!!
解决方法
您可以使用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();