在Java 8中使用Lambda迭代地图吗? [英] Iterate though a Map of Maps with Lambda in Java 8?

查看:134
本文介绍了在Java 8中使用Lambda迭代地图吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是java和lambda的新手,我想在地图的地图中找到值的总和和平均值。

I am new to java and lambda, I want to find the sum and average of values in a map of maps.

我的对象就像 Map< String,Map< String,Double>> browserData;

数据的格式为

<Chrome, <UK, 2.90>>
<Chrome, <US, 5.20>>
<Chrome, <EU, -0.25>>
<IE, <UK, 0.1>>
<IE, <US, -.20>>
<IE, <EU, 0.00>>
<FF, <UK, 0.90>>
<FF, <US, 1.20>>
<FF, <EU, 1.25>>

最终结果需要是两张地图,1表示总和,另一张表示平均值

The final result needs to be two maps, 1 for sum and another for average

map1 = <CountryName, SumValue>

map2 = <CountryName, AverageValue>

所以上面例子的结果是

map1 = <UK, 3.9>
       <US, 6.2>
       <EU, 1>

map2 = <UK, 1.3>
       <US, 2.07>
       <EU, 0.33>

我如何实现这一目标?

推荐答案

想法是流式传输内部地图的每个条目并应用适当的收集器来计算您需要的值:

The idea is to stream each of the entries of the inner maps and apply the appropriate collector to calculate the values you need:

Map<String, DoubleSummaryStatistics> stats = browserData.values().stream()
        .flatMap(m -> m.entrySet().stream()) //Stream the inner maps' entrySets
        .collect(groupingBy(Entry::getKey, summarizingDouble(Entry::getValue)));
DoubleSummaryStatistics ds = stats.getOrDefault("EU", new DoubleSummaryStatistics());
System.out.println("sumEu = " + ds.getSum());
System.out.println("avgEu = " + ds.getAverage());

如果您确实需要单独的总和和平均地图,您可以从摘要地图创建它们: / p>

If you do need the individual sum and average maps, you can create them from the summary map:

Map<String, Double> map1 = stats.entrySet().stream()
        .collect(toMap(Entry::getKey, e -> e.getValue().getSum()));
Map<String, Double> map2 = stats.entrySet().stream()
        .collect(toMap(Entry::getKey, e -> e.getValue().getAverage()));

注意:我使用了以下静态导入:

import static java.util.stream.Collectors.groupingBy;

import static java.util.stream.Collectors.summarizingDouble;

import static java.util.stream.Collectors.toMap;

这篇关于在Java 8中使用Lambda迭代地图吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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