Java 8流API - 是否有标准方法将Map中的每个值处理为不同的类型?

gav*_*koa 5 java java-8

我学习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)

Bri*_*etz 9

你要:

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的函数.