简体   繁体   English

Guava Multimap 的每个值的总和

[英]Sum of each values of Guava Multimap

I created a Guava Multimap ListMultimap<String,String> sampleMultimap = ArrayListMultimap.create();我创建了一个番石榴多图ListMultimap<String,String> sampleMultimap = ArrayListMultimap.create(); And added some values which I take from a text file.并添加了一些我从文本文件中获取的值。 Now as an output I have现在作为输出我有

{Football=[10], Basketball=[1210, 1210, 1210, 120], Tennis=[1, 10, 100, 1000]}

I would like to sum each of the sports and find the highest sum.我想对每项运动求和并找到最高的总和。 So expected result is所以预期的结果是

Basketball: 3750

Somehow I am stuck because I cant get the each one with samleMultimap.get(x) because key values are unknown and comes form text file.不知何故,我被卡住了,因为我无法使用samleMultimap.get(x)获取每个值,因为键值未知并且来自文本文件。 Is there any way to get the expected result?有什么办法可以得到预期的结果吗?

In the end you want Map<String, Integer> where values are sums of original multimap.最后你想要Map<String, Integer> ,其中值是原始多图的总和。 You can use couple views:您可以使用几个视图:

Note that if you want to perform many operations on resulted map , read caveat in documentation and for example do ImmutableMap.copyOf(map) :请注意,如果您想对结果map执行许多操作,请阅读文档中的警告,例如执行ImmutableMap.copyOf(map)

The function is applied lazily, invoked when needed.该函数被延迟应用,在需要时调用。 This is necessary for the returned map to be a view, but it means that the function will be applied many times for bulk operations like Map.containsValue(java.lang.Object) and Map.toString() .这对于返回的地图是一个视图是必要的,但这意味着该函数将被多次应用于批量操作,如Map.containsValue(java.lang.Object)Map.toString() For this to perform well, function should be fast.为了让这个表现良好,函数应该很快。 To avoid lazy evaluation when the returned map doesn't need to be a view, copy the returned map into a new map of your choosing.为了在返回的地图不需要是视图时避免延迟评估,请将返回的地图复制到您选择的新地图中。

With a ListMultimap you can call asMap() to get a view as a java.util.Map , then do normal map things.使用ListMultimap您可以调用asMap()以获取java.util.Map的视图,然后执行法线映射操作。

If you change sampleMultimap to be an ArrayListMultimap instead of ListMultimap , then you can call keySet() directly (skip the asMap() call) and iterate over the resulting keys.如果您将sampleMultimap更改为ArrayListMultimap而不是ListMultimap ,那么您可以直接调用keySet() (跳过asMap()调用)并迭代结果键。

Here's an example showing how you could get each key from a ListMultimap (even if the underlying implementation is an instance of ArrayListMultimap ), then get each associated value:这是一个示例,展示了如何从ListMultimap获取每个键(即使底层实现是ArrayListMultimap的实例),然后获取每个关联的值:

ListMultimap<String,String> sampleMultimap = ArrayListMultimap.create();
Map<String,String> mapView = sampleMultimap.asMap();
for (String key : mapView.keySet()) {
    String value = mapView.get(key);
    // do something with value
}

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

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