title: Java lambda expressions and memory allocation
body: <p>Let's say we have three methods like these. They all do the same, but how different they are in terms of memory allocation and efficiency? Method one will create instances of Function during each call, but will the second method do the same? Should one always use the third version or either version is safe and the JIT compiler will take care of the memory optimization?</p>
  
  <pre><code>class Test {
      Map&lt;String, Set&lt;String&gt;&gt; mapOfSets = new HashMap&lt;&gt;();
      static final Function&lt;String, Set&lt;String&gt;&gt; FUNCTION = s -&gt; new HashSet&lt;&gt;();
  
      void method1(String key, String value) {
          Function&lt;String, Set&lt;String&gt;&gt; func = s -&gt; new HashSet&lt;&gt;();
          mapOfSets.computeIfAbsent(key, func).add(value);
      }
  
      void method2(String key, String value) {
          mapOfSets.computeIfAbsent(key, s -&gt; new HashSet&lt;&gt;()).add(value);
      }
  
      void method3(String key, String value) {
          mapOfSets.computeIfAbsent(key, FUNCTION).add(value);
      }
  }
  </code></pre>