2015-07-21 76 views
0

在HashMap中<字符串,列表 >每一行的值的余有一个HashMap中的这种格式: HashMap<String, List<RrdData>> myData 萨姆在Java

{Data1=[ [Time=1437479200, value=0.8], [Time=1437479201, value=12]], Data2=[[Time=1437479200, value=123], [Time=1437479201, value=78]], Data3=[[fetchTime=1437479200, value=789], [Time=1437479201, value=45]} 

我要总结的所述第一值的每个数据,那么第二个值等等。例如:(数组列表的大小不是静态的)

Data1.firstalue + Data2.firstValue+ Data3.firstValue. 
Data1.secondValue + Data2.secondValue + Data3.secondValue 

所以采用垂直计算的形式。 我写的是它的水平版本。我怎样才能改变它垂直的方式?

for (Entry<String, List<RrdData>> counterEntry : myData.entrySet()) { 
    final List<RrdData> tempValues = counterEntry.getValue(); 
    for (int i=0; i<length; i++) { 
     sum += tempValues.getValue(i); 
    }  
} 

回答

1

首先找到最长的counterEntry列表。然后做

for (int i = 0; i<longestLength;i++){ 
    for (List<RrdData> counterEntry : myData.getValues()) { 
     if(counterEntry.size() > i){ 
      sum += counterEntry.getValue(i); 
     } 

    } 
    System.out.println(sum); 
    sum = 0; 
} 

当然,这将是相当缓慢(因为你必须遍历整个列表中的每个条目)。但编程和理解起来很容易。

如果你愿意,你可以做一个更快的方法:既节约了所有款项清单

List<Integer> sums = ArrayList<Integer>(); 

for (List<RrdData> counterEntry : myData.getValues()) { 
    for (int i = 0; i<counterEntry.size(); i++) { 
     if(sums.size > i){ 
      sums.get(i) += counterEntry.getValue(i); 
     }else 
      sums.add(counterEntry.getValue(i); 
    } 
} 

+0

感谢您的回答。但我有点失落。 d.getValue(i)中的d是什么;? – shirin

+0

对不起。从你的代码中复制了一点点。我现在更新了它。 – Astrogat

+0

但我想要这种形式的值:Data1.firstalue + Data2.firstValue + Data3.firstValue。你提供的总和值为 – shirin