title: Java 8 Streams and try with resources
body: <p>I thought that the stream API was here to make the code easier to read.
  I found something quite annoying. The <code>Stream</code> interface extends the <code>java.lang.AutoCloseable</code> interface.</p>
  
  <p>So if you want to correctly close your streams, you have to use try with resources.</p>
  
  <p><em>Listing 1</em>. Not very nice, streams are not closed.</p>
  
  <pre><code>public void noTryWithResource() {
      Set&lt;Integer&gt; photos = new HashSet&lt;Integer&gt;(Arrays.asList(1, 2, 3));
  
      @SuppressWarnings("resource") List&lt;ImageView&gt; collect = photos.stream()
          .map(photo -&gt; new ImageView(new Image(String.valueOf(photo))))
          .collect(Collectors.&lt;ImageView&gt;toList());
  }
  </code></pre>
  
  <p><em>Listing 2</em>. With 2 nested try</p>
  
  <pre><code>public void tryWithResource() {
      Set&lt;Integer&gt; photos = new HashSet&lt;Integer&gt;(Arrays.asList(1, 2, 3));
  
      try (Stream&lt;Integer&gt; stream = photos.stream()) {
          try (Stream&lt;ImageView&gt; map = stream
                  .map(photo -&gt; new ImageView(new Image(String.valueOf(photo)))))
          {
              List&lt;ImageView&gt; collect = map.collect(Collectors.&lt;ImageView&gt;toList());
          }
      }
  }
  </code></pre>
  
  <p><em>Listing 3</em>. As <code>map</code> returns a stream, both the <code>stream()</code> and the <code>map()</code> functions have to be closed.</p>
  
  <pre><code>public void tryWithResource2() {
      Set&lt;Integer&gt; photos = new HashSet&lt;Integer&gt;(Arrays.asList(1, 2, 3));
  
      try (Stream&lt;Integer&gt; stream = photos.stream(); Stream&lt;ImageView&gt; map = stream.map(photo -&gt; new ImageView(new Image(String.valueOf(photo)))))
      {
          List&lt;ImageView&gt; collect = map.collect(Collectors.&lt;ImageView&gt;toList());
      }
  }
  </code></pre>
  
  <p>The example I give does not make any sense. I replaced <code>Path</code> to jpg images with <code>Integer</code>, for the sake of the example. But don't let you distract by these details.</p>
  
  <p>What is the best way to go around with those auto closable streams.
  I have to say I'm not satisfied with any of the 3 options I showed.
  What do you think? Are there yet other more elegant solutions?</p>