Amit Gupta Amit Gupta - 4 years ago 157
Java Question

How to iterate through google multimap

I have to iterate through google multimap. But


  1. I am using jdk 1.4 and can't switch to higher version. So i can not use generic features.

  2. My multimap can have multiple values for a key.

  3. There might be a situation when a value of multimap is multimap in itself


Answer Source

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.

You can iterate through all values:

for (Object value : multimap.values()) { ... }

Or all keys (a key that maps to multiple values coming up multiple times in the iteration):

for (Object key : multimap.keys()) { ... }

Or the key set:

for (Object key : multimap.keySet()) { ... }

Or the entries:

for (Map.Entry entry : multimap.entries()) { ... }

Or the value Collections:

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 Iterators directly.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download