【发布时间】:2018-05-01 19:43:53
【问题描述】:
我正在尝试使用 java 流将下面的嵌套 for 循环转换为 hashmap,但我在收集器步骤中被击中。你能帮忙吗?
现有代码:
private static HashMap<String, Long> getOutput(List<Employee> eList) {
HashMap<String, Long> outputList = new HashMap<>();
for (Employee employee : eList) {
List<Department> departmentList = employee.getDepartmentList();
for (Department department : departmentList) {
if (department.getType().equals(DepartmentType.SCIENCE)) {
outputList.put(employee.getName(),department.getDepartmentId()));
}
}
}
return outputList;
}
到目前为止我尝试过:
private static HashMap<String, Long> getOutput(List<Employee> eList) {
return eList.stream()
.flatMap(emp -> emp.getDepartmentList().stream()
.filter(dept -> dept.getType().equals(DepartmentType.SCIENCE))
.collect(HashMap::new, ???)
}
【问题讨论】:
-
这可能会为您指明正确的方向stackoverflow.com/a/20887747/4252352
-
您现有的代码不起作用。
outputList和OutputList的拼写不一致,而且它的类型Map与方法的返回类型HashMap不匹配。如果这是“现有代码”,是什么阻止了您从 IDE 中简单地复制工作代码而不是在浏览器中对其进行原型设计? -
@Holger,感谢您指出错误。实际上我无法粘贴生产代码,所以我将 Employee 和 Department 原型作为示例。修复问题中的复制粘贴错误。
标签: java java-stream