[英]Stream on List to get element and also from inner elements
我有一個從 Json 填充的員工List
object。
{
"emp": [
{
"name": "John",
"id": "123",
"reportingEmp": [
{
"name": "Mark",
"id": "342"
},
{
"name": "Mike",
"id": "342"
},
{
"name": "Lindsey",
"id": "342"
}
]
},
{
"name": "Steve",
"id": "123"
},
{
"name": "Andrew",
"id": "123"
}
]
}
class Employee {
private String name;
private String id;
private List<Employee> reportingEmp;
}
現在我想獲取所有雇員的姓名,包括 stream 中的報告雇員。
我可以使用下面的方法獲取所有員工,但它會錯過報告員工
List<String> names = emp.stream().map(Employee::getName).collect(toList());
但上面只會給John,Steve and Andrew
但我想要下面的列表
John
Mark
Mike
Lindsey
Steve
Andrew
flatMap
是要使用的東西,當你想要 map 一個東西(一個Employee
)到多個東西(員工的名字+所有報告員工的名字)。
在flatMap
lambda 中,你只需要創建一個 stream 包含你想要 map 該員工的東西,所以:
List<String> names = employees.stream().flatMap(emp ->
Stream.concat(
// the employee's name,
Stream.of(emp.getName()), // and
// the employee's reporting employees' names
emp.getReportingEmp().stream().map(Employee::getName)
)
).collect(Collectors.toList());
如果getReportingEmp
可以返回null
,那么你可以這樣做:
List<String> names = employees.stream().flatMap(emp ->
Stream.concat(
Stream.of(emp.getName()),
Optional.ofNullable(emp.getReportingEmp()).map(
x -> x.stream().map(Employee::getName)
).orElse(Stream.of())
)
).collect(Collectors.toList());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.