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

只愿长相守 提交于 2021-02-17 06:02:38

问题


I am reading from a huge csv file which contains duplicate entries. I was able to read the whole csv file into a 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

Returns a view collection of all key-value pairs contained in this multimap, as Map.Entry instances

but I am unable to get anything from it.

I am using ArrayListMultiMap implementation of MultiMap. Reason for using ArrayList is that later I need to perform a search operation which is quicker in an ArrayList.

I have pstored the keyset as a MultiSet which is why I am able to get all the duplicate keys.

Value of each of the keys is an object which I want to be written to a file corresponding to that read key.


回答1:


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
}



回答2:


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. In the documentation, Google stresses that the latter approach is preferred, although if you do multimap.asMap().entries() (N.B. Not just multimap.entries()), as Louis suggested, you will have entries like the former version.

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...
}


来源:https://stackoverflow.com/questions/32235539/how-do-i-get-each-of-the-entries-from-guava-multimap-and-their-corresponding-val

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!