简体   繁体   English

如何从Guava MultiMap中获取每个条目以及与之关联的相应值?

[英]How do I get each of the entries from Guava MultiMap and their corresponding values associated with it?

I am reading from a huge csv file which contains duplicate entries. 我正在从包含重复条目的巨大csv文件中读取。 I was able to read the whole csv file into a Multimap . 我能够将整个csv文件读取到Multimap I am also able to obtain the keyset with duplicate values and write them to a file. 我还能够获取具有重复值的键集并将它们写入文件。 I want to get the value associated with each of the keys and write it to a file but unable to do so. 我想获取与每个键关联的值,并将其写入文件,但无法这样做。 I cant seem to find any of the options that might help me. 我似乎找不到任何可能对我有帮助的选项。 I tried using entries() method which according to the doc 我尝试根据文档使用entries()方法

Returns a view collection of all key-value pairs contained in this multimap, as Map.Entry instances Map.Entry实例的形式返回此Multimap中包含的所有键值对的视图集合。

but I am unable to get anything from it. 但我无法从中得到任何东西。

I am using ArrayListMultiMap implementation of MultiMap . 我正在使用MultiMap ArrayListMultiMap实现。 Reason for using ArrayList is that later I need to perform a search operation which is quicker in an ArrayList . 使用ArrayList原因是,稍后我需要执行在ArrayList更快的搜索操作。

I have pstored the keyset as a MultiSet which is why I am able to get all the duplicate keys. 我将密钥集存储为一个MultiSet ,这就是为什么我能够获得所有重复密钥的原因。

Value of each of the keys is an object which I want to be written to a file corresponding to that read key. 每个键的值是一个对象,我想将其写入对应于该读取键的文件中。

If you want each key and each value associated with that key, instead of each key-value pair, then you can do that with 如果要每个键和与该键关联的每个值,而不是每个键值对,则可以使用

for (Map.Entry<String, Collection<SomeClassObject>> entry : multimap.asMap().entrySet()) {
   String key = entry.getKey();
   Collection<SomeClassObject> valuesForKey = entry.getValue();
   // do whatever
}

As you've discovered, there are two ways to think about Multimaps. 正如您所发现的,有两种方法可以考虑多图。 One is as a Map<K, Collection<V>> , and the other is as a Map<K, V> , where the keys do not have to be unique. 一个是作为Map<K, Collection<V>> ,另一个是作为Map<K, V> ,其中键不必唯一。 In the documentation , Google stresses that the latter approach is preferred, although if you do multimap.asMap().entries() (NB Not just multimap.entries() ), as Louis suggested, you will have entries like the former version. 文档中 ,Google强调了后一种方法是首选的,尽管如果您执行multimap.asMap().entries() (注意,不只是multimap.entries() )(如Louis所建议的那样),您将拥有类似于前一种版本的条目。

For your particular problem, I'm not sure why you can't do something like the following: 对于您的特定问题,我不确定为什么您不能执行以下操作:

for (String key : multimap.keySet()) {
    Collection<SomeClassObject> values = multimap.get(key);
    //Do whatever with all the values for Key key...
}

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

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