title: Iterating over a HashMap of HashMaps in Java (or Scala)
body: <p>I created a class <code>Foo</code> that has the method <code>toArray()</code> that returns an <code>Array&lt;Int&gt;</code>.</p>
  
  <p>Now, I have a HashMap mapping Strings to HashMaps, which map Objects to Foo. That is:</p>
  
  <pre><code>HashMap&lt;String,HashMap&lt;Object,Foo&gt;&gt;
  </code></pre>
  
  <p>And I want to create a new object of type:</p>
  
  <pre><code>HashMap&lt;String,HashMap&lt;Object,Array&lt;Int&gt;&gt;&gt;
  </code></pre>
  
  <p>That is obtained by calling the function toArray() for every element Foo in the original HashMAp.</p>
  
  <p>To do so I normally would do something like:</p>
  
  <pre><code>    public static HashMap&lt;String,HashMap&lt;Object,Array&lt;Int&gt;&gt;&gt; changeMap(Map mpOld) {
          Object key2;
          String key1;
          Iterator it2;
          HashMap&lt;String,HashMap&lt;Object,Array&lt;Int&gt;&gt;&gt; mpNew= 
              new HashMap&lt;String,HashMap&lt;Object,Array&lt;Int&gt;&gt;&gt;()
          Iterator it1 = mpOld.keySet().iterator();
          while (it1.hasNext()) {
              key1=it1.next();
              it2= mpOld.get(key1).keySet().iterator();
              mpNew.put(key1,new HashMap&lt;Object,Array&lt;Int&gt;&gt;())
              while (it2.hasNext()) {
                  key2=it2.next();
                  mpNew.get(key1).put(key2,mpOld.get(key1).get(key2).toArray());
                  //TODO clear entry mpOld.get(key1).get(key2)
              }
              //TODO clear entry mpOld.get(key1)
          }
          return mpNew;
      }
  </code></pre>
  
  <p>A similar code works just fine, but the Size of the HashMap is too big to hold two of them in memory. As you can see I added two points where I want to clear some entries. The problem is, if I do, I get either a concurrency error, or the iterator loop just terminates.</p>
  
  <p>I wonder if there is a better way to iterate through the Maps and copy the information.</p>
  
  <p>Also, I'm working in a Scala project but here I have to use Java types for some compatibility issues. Although <code>Java.util.HashMap</code> is not an iterator, maybe Scala has some hidden functinality to deal with this?</p>
  
  <p>Thanks,</p>