简体   繁体   English

如何使用 Guava 的 ListMultimap 对键列表中的元素求和

[英]How to sum elements from a Key List using ListMultimap from Guava

Example:例子:

I want to sum the elements inside every key, which is basically an ArrayList of elements "double numbers".The Guava ArrayListMultimap is declared in this way:我想对每个键内的元素求和,这基本上是元素“双数”的ArrayList。Guava ArrayListMultimap以这种方式声明:

ListMultimap <String, Double> multimap = LinkedListMultimap.create(); 

and displayed like this "3 keys of ArrayList":并像这样显示“ArrayList 的 3 个键”:

HH_0=[0.1, 0.4, 0.2, 0.3, 0.1], 
HH_1=[0.1,0.2], 
HH_2=[0.1] 

The summation should be stored in an array or any simple structure like this output:总和应存储在数组或任何简单结构中,如以下输出:

array_sum=[1.1,0.3,0,1]

the actual size of multimap is 8 and not 3 because if any key has more than one value in its arraylist, means the key is duplicate and that's reason of using multimap of Guava , it can store duplicated keys with multiple (different or same) values in an ArrayList with the contrary in case of a simple Hashmap. multimap的实际大小是8而不是3 ,因为如果任何键在其数组列表中有多个值,则意味着该键是重复的,这就是使用Guavamultimap的原因,它可以存储具有多个(不同或相同)值的重复键在ArrayList中与简单Hashmap 的情况相反。

My essay:我的作文:
I extracted the keys in array_Str of Strings to compare with.我提取了字符串array_Str中的键进行比较。 We suppose the length of the wanted array_sum[ ] is already initiated with 3:我们假设所需的array_sum[ ]的长度已经从 3 开始:

double sum = 0.0;
String array_Str = {"HH_0","HH_1","HH_2"};

       for (int i = 0; i < array_sum.length; i++) {
           for (Entry<String, Double> entry : multimap.entries())  {
               
               
           if( entry.getKey().equals(array_sum[i])) {
               
               sum=sum+ entry.getValue();
           }
               
           }
           array_sum[i]=sum;   
       }

Any guidance is very appreciated.非常感谢任何指导。

Using Java 8 streams to simplify just a little:使用 Java 8 流来简化一点:

for (int i = 0; i < array_str.length; i++) {
  array_sum[i] = multimap.get(array_str[i]).stream().mapToDouble(d -> d).sum();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM