Java 8流API - 是否有标准方法将Map中的每个值处理为不同的类型? [英] Java 8 stream API - is there standard method for processing each value in Map to different type?

查看:105
本文介绍了Java 8流API - 是否有标准方法将Map中的每个值处理为不同的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我学习 Java 8 Lambda表达式流API 。为了理解我尝试使表达模拟为SQL问题:

I learn Java 8 Lambda Expressions and stream API. In order to understand I try to make expression analog for SQL quesry:

select department, avg(salary) from employee group by department

private static class Employee {
    public String name;
    public String department;
    public int salary;
}

官方教程中提供的解决方案:

Solution present in official tutorial:

empls.stream().collect(
    Collectors.groupingBy(
        x -> x.department,
        Collectors.averagingInt(x -> x.salary)))

在我找到此解决方案之前,我采用分组计算平均值的策略:

Before I found this solution my strategy to calculate average with grouping:

Map<String, List<Employee>> tmp =
    empls.stream().collect(Collectors.groupingBy(x -> x.department));

并将functor应用于每个值。但是在 Map 界面中,没有方法可以将值转换为不同的类型。在我的情况下,将列表减少到 Double 。标准SE API仅提供方法 replaceAll()将值转换为相同类型...

and applying functor to each value. But in Map interface there are no method to transform value into different type. In my case reduce List to Double. Standard SE API provide only method replaceAll() that convert value to same type...

要转换的Java 8样式方法/技巧/单行内容值映射到不同的类型?像伪代码一样工作:

What Java 8 style method/trick/one-liner to convert Map value into different type? Worked like pseudo-code:

Map<K, V2> map2 = new HashMap<>();
for (Map.Entry<K, V1> entry : map1.entrySet()) {
     map2.add(entry.getKey(), Function<V1, V2>::apply(entry.getValue()));
 }


推荐答案

你想:

Map<K, V2> map2 = 
    map1.entrySet().stream()
        .collect(toMap(Map.Entry::getKey, 
                       e -> f.apply(e.getValue()));

其中f是从V到V2的函数。

where f is a function from V to V2.

这篇关于Java 8流API - 是否有标准方法将Map中的每个值处理为不同的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆