title: Java collection and memory optimization
body: <p>I wrote a custom index to a custom table which uses 500MB of heap for 500k strings.  Only 10% of the strings are unique; the rest are repeats. Every string is of length 4.</p>
  
  <p>How i can optimize my code?  Should I use another collection?   I tried to implement a custom string pool to save memory:</p>
  
  <pre><code>public class StringPool {
  
      private static WeakHashMap&lt;String, String&gt; map = new WeakHashMap&lt;&gt;();
  
      public static String getString(String str) { 
          if (map.containsKey(str)) {
              return map.get(str);
          } else {
              map.put(str, str);
              return map.get(str);
          }
      }
  }
  
  private void buildIndex() {
          if (monitorModel.getMessageIndex() == null) {
              // the index, every columns create an index
              ArrayList&lt;HashMap&lt;String, TreeSet&lt;Integer&gt;&gt;&gt; messageIndex = new ArrayList&lt;&gt;(filterableColumn.length);
              for (int i = filterableColumn.length; i &gt;= 0; i--) {
                  // key -&gt; string,   value -&gt; treeset, the row wich contains the key
                  HashMap&lt;String, TreeSet&lt;Integer&gt;&gt; hash = new HashMap&lt;&gt;();
                  messageIndex.add(hash);
              }
              // create index for every column
              for (int i = monitorModel.getParser().getMyMessages().getMessages().size() - 1; i &gt;= 0; --i) {
                  TreeSet&lt;Integer&gt; tempList;
  
                  for (int j = 0; j &lt; filterableColumn.length; j++) {
                      String value  = StringPool.getString(getValueAt(i, j).toString());
                      if (!messageIndex.get(j).containsKey(value)) {
                          tempList = new TreeSet&lt;&gt;();
                          messageIndex.get(j).put(value, tempList);
                      } else {
                          tempList = messageIndex.get(j).get(value);
                      }
  
                      tempList.add(i);
                  }
              }
              monitorModel.setMessageIndex(messageIndex);
          }
      }
  </code></pre>