[英]Stream on List to get element and also from inner elements
I have a List
of Employee object populated from a Json.我有一个从 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;
}
Now I wanted to get the names of all employess including the reporting employees in a stream.现在我想获取所有雇员的姓名,包括 stream 中的报告雇员。
I can use the below to get all the employees but it would miss the reporting employees我可以使用下面的方法获取所有员工,但它会错过报告员工
List<String> names = emp.stream().map(Employee::getName).collect(toList());
But the above would give only John,Steve and Andrew
but I want the below list但上面只会给John,Steve and Andrew
但我想要下面的列表
John
Mark
Mike
Lindsey
Steve
Andrew
flatMap
is the thing to use, when you want to map one thing (an Employee
) to multiple things (the employee's name + all the reporting employees' names). flatMap
是要使用的东西,当你想要 map 一个东西(一个Employee
)到多个东西(员工的名字+所有报告员工的名字)。
In the flatMap
lambda, you just need to create a stream that contains the things you want to map that employee to, so:在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());
If getReportingEmp
can return null
, then you can do:如果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.