我学习Java 8 Lambda表达式和流API.为了理解我试着使表达模拟SQL问题:
select department, avg(salary) from employee group by department
Run Code Online (Sandbox Code Playgroud)
对于:
private static class Employee {
public String name;
public String department;
public int salary;
}
Run Code Online (Sandbox Code Playgroud)
官方教程中的解决方案:
empls.stream().collect(
Collectors.groupingBy(
x -> x.department,
Collectors.averagingInt(x -> x.salary)))
Run Code Online (Sandbox Code Playgroud)
在我找到这个解决方案之前,我采用分组计算平均值的策略:
Map<String, List<Employee>> tmp =
empls.stream().collect(Collectors.groupingBy(x -> x.department));
Run Code Online (Sandbox Code Playgroud)
并将仿函数应用于每个值.但是在Map
界面中没有将值转换为不同类型的方法.在我的情况下减少列表到Double
.标准SE API仅提供将值转换为相同类型的方法replaceAll() ...
什么Java 8样式方法/技巧/单行将Map
值转换成不同类型?像伪代码一样工作:
Map<K, V2> map2 = new HashMap<>();
for (Map.Entry<K, V1> entry : map1.entrySet()) {
map2.add(entry.getKey(), Function<V1, V2>::apply(entry.getValue()));
}
Run Code Online (Sandbox Code Playgroud)
你要:
Map<K, V2> map2 =
map1.entrySet().stream()
.collect(toMap(Map.Entry::getKey,
e -> f.apply(e.getValue()));
Run Code Online (Sandbox Code Playgroud)
其中f是从V到V2的函数.