title: treemap vs hashmap and sort in terms of memory usage
body: <p>I have a huge file in the format:</p>
  
  <pre><code>x a
  y c
  x d
  z a
  z s
  y k
  </code></pre>
  
  <p>I want that the output will be <em>sorted</em> and in the form</p>
  
  <pre><code>x a,d
  y c,k
  z a,s,k
  </code></pre>
  
  <p>For this type of task a hash is the best:</p>
  
  <p>The straightforward TreeMap solution would be this:</p>
  
  <pre><code>Map&lt;String, StringBuilder&gt; agg = Maps.newTreeMap();
  
  while ((line = r.readLine()) != null) {
  
      String[] arr = line.split("\t");
              String key = arr[0];
              String value = arr[1];
  
      if(agg.containsKey(key)) {
              agg.get(key).append(",").append(value);
          }
          else {
              agg.put(key, new StringBuilder(value));
          }
      }
  
  }
  r.close();
  
  
  System.out.println("Printing results");
  FileWriter f = new FileWriter("out.txt");
  
  for (String key : agg.keySet()) {
      f.write(key+"\t"+agg.get(key)+"\n");
  }
  </code></pre>
  
  <p>Another option would be to use a hashmap, take the keyset, sort it and iterate over it.</p>
  
  <p>The different part would be</p>
  
  <pre><code>    System.out.println("Sorting array");
      List&lt;String&gt; keys = Lists.newArrayList(agg.keySet());
              Collections.sort(keys);
          System.out.println("Printing results");
          FileWriter f = new FileWriter("out.txt");
  
          for (String key : keys) {
              f.write(key+"\t"+agg.get(key)+"\n");
          }
  </code></pre>
  
  <p>For me the big O is less important because it is a batch job. </p>
  
  <p>For me the memory usage is much more important.</p>
  
  <p>Which strategy is more efficient in terms of memory?</p>
  
  <p>HashMap and the peek in the sort phase or the TreeMap approach</p>