title: How to create a csv file from ConcurrentHashMap<String, Integer> in Java?
body: <p>I need to create a single string named  CSVOutput, and load all keys and values from the <code>ConcurrentHashMap&lt;String, Integer&gt;</code>, counts into this file separated by commas.
  So I'll have two columns in the resulting csv file, one is for the keys and the other one for the values.</p>
  <p>I have written this code for my method OutputCountsAsCSV:</p>
  <pre class="lang-java prettyprint-override"><code>private void OutputCountsAsCSV(ConcurrentHashMap&lt;String, Integer&gt; counts, String filename) {
      String CSVOutput = new String(&quot;&quot;);
      for (Entry&lt;String, Integer&gt; entry : counts.entrySet()) {
          String rowText = String.format(&quot;%s,%d\n&quot;, entry.getKey(), entry.getValue());  # defines new lines/rows
          CSVOutput += rowText;
          try (FileWriter writer = new FileWriter(filename)) {
              writer.write(CSVOutput);
          }
          catch (Exception e) {
              System.out.println(&quot;Saving CSV to file failed...&quot;);
          }
      }
      System.out.println(&quot;CSV File saved successfully...&quot;);
  }
  </code></pre>
  <p>However, I'm told I should have followed this order:</p>
  <ol>
  <li>create and prepare file</li>
  <li>for each entry, write data to file</li>
  <li>close the file (and print that it happened successfully).</li>
  </ol>
  <p>Indeed, my <code>System.out.println(&quot;CSV File saved successfully...&quot;)</code> seems to be inside the loop and is being printed many times.</p>
  <p>How can I do it correctly?</p>
  <p>I am a beginner in Java, so I'm very grateful for any help.</p>