title: Adding elements to an HashMap concurrently
body: <p>If I iterate over a standard <code>HashMap</code> and attempt to add elements to it while iterating I get <code>ConcurrentModificationException</code>.</p>
  
  <p>So I try an HashMap allowing concurrent adds:</p>
  
  <pre><code>ConcurrentHashMap&lt;String, Integer&gt; cMap = new ConcurrentHashMap&lt;&gt;();
  cMap.put("one", 1);
  cMap.forEach((key, value) -&gt; cMap.put(key + key, value + value));
  System.out.println(cMap);
  </code></pre>
  
  <p>However, the resulting map is a bit weird:</p>
  
  <pre><code> {oneoneoneoneoneoneoneone=8, one=1, oneone=2, oneoneoneone=4}
  </code></pre>
  
  <p>and if changing the key to zx (<code>cMap.put("zx", 1)</code>), the result is now:</p>
  
  <pre><code>{zxzx=2, zx=1}
  </code></pre>
  
  <p>Questions:</p>
  
  <p>1) Why this happens? The two concurrent operations (iterating and adding) should not conflict.</p>
  
  <p>2) How to fix the inconsistency?</p>
  
  <p>As opposite to Collections, when changing a String while iterating over the chars of that String, this issue is not being met:</p>
  
  <pre><code>        String str = scanner.next();
          for (int i = 1; i &lt; str.length(); i++) {
              if (str.charAt(i) == str.charAt(i-1)) {
                  str = str.substring(0, i-1) + str.substring(i+1);
                  i = 0;
              }
          }
          if (str.length() == 0) {
              System.out.println("Empty String");
          } else {
              System.out.println (str);
          }
      }
  </code></pre>
  
  <p><strong>note that in the above loop, the source String isn't actually changed but re-assigned because String is immutable and can not be modified</strong>.</p>
  
  <p>The above code works fine and consistently. Is this an example of why Strings are thread safe?</p>