问题
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