I have to iterate through google multimap. But
Maps don't keep the order of items. This is the contract of MultiMap s... This is the price to pay for query-in performances. One option is to use Map<String, List<String>> instead.
A Multimap is a new collection type that is found in Google's Guava library for Java. A Multimap can store more than one value against a key. Both the keys and the values are stored in a collection, and considered to be alternates for Map<K, List<V>> or Map<K, Set<V>> (standard JDK Collections Framework).
Following is a simple custom implementation of the Multimap class in Java using a Map and a Collection . * Add the specified value with the specified key in this multimap. * Returns the Collection of values to which the specified key is mapped, * or null if this multimap contains no mapping for the key.
Google Collections (now Guava) is a Java 1.5 library... even ignoring the lack of generics in Java 1.4, it likely uses things that were added in 1.5, making it incompatible. That said, there are various ways to iterate through a Multimap
.
By key, collection pairs in Java8:
multimap.asMap().forEach((key, collection) -> {...});
Iterate through all values:
for (Object value : multimap.values()) { ... }
Iterate through all keys (a key that maps to multiple values coming up multiple times in the iteration):
for (Object key : multimap.keys()) { ... }
Iterate through the key set:
for (Object key : multimap.keySet()) { ... }
Iterate through the entries:
for (Map.Entry entry : multimap.entries()) { ... }
Iterate through the value Collection
s:
for (Collection collection : multimap.asMap().values()) { ... }
You can also get the corresponding Collection
for each key in the keySet()
using get
as described by bwawok.
Edit: I didn't think about the fact that Java 1.4 didn't have the foreach loop either, so of course each loop above would have to be written using the Iterator
s directly.
I am on Java 6, but this should be pretty close... sorry if I missed something java 1.4ish
Set keySet = listmultimap.keySet(); Iterator keyIterator = keySet.iterator(); while (keyIterator.hasNext() ) { String key = (String) keyIterator.next(); List values = listmultimap.get( key ); }
Each get will get you everything back that matched that key. Then you can either peel those off, or do whatever you want with them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With