views:

74

answers:

2

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
+2  A: 

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.

bwawok
There is a single problem with my code. My HashMultimap may have HashMultimap as a value. and get() returns Set. I am not able to cast it again to HashMultimap for recursion.
articlestack
Can you describe the use case of a multimap of multimaps :) Seems like maybe you could rethink it to be a more sane data structure, no?
bwawok
I am converting a XML file(small in size, so no prob) into a multimap. Since a tag can have tags inside. So a multimap can have multimap inside.
articlestack
There are quite a few "fast" java XML parsers. Have you tried any of them? I guess it depends on what questions you want to ask the XML, but for just looping through and doing stuff with it, the normal XML parsing libraries seem easier....
bwawok
Use a HashMultimap only when the values are immutable (at least to the extent that the hash code can't change). If the values are multimaps, define an ArrayListMultimap<K, Multimap> instead. On that multimap, get() returns a List<Multimap>.
Jared Levy
@bwawok: i dint found any parser which can do this sort of conversion. If someone is in ur mind tell me.
articlestack
I recommend using regex to parse XML into a nested multimap structure. ;)
Rosarch
+2  A: 

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.

ColinD