title: Using Optional with Streams in Java
body: <p>I was trying to refactor an old code to use streams, and my first approach was this:</p>
  
  <pre><code>public void run() throws IOException {
     Files.list(this.source)
          .filter(Images::isImage)
          .map(Image::new)
          .filter(image -&gt; image.isProportional(this.height, this.width))
          .map(image -&gt; image.resize(this.height, this.width))
          .forEach(image -&gt; Images.write(image, this.destination));
  }
  </code></pre>
  
  <p>This is not compiling since new Image() and Images.write() throws IOExceptions.</p>
  
  <p>Wrapping those exceptions with UncheckedIOException wouldn't do the trick as I don't want to stop other images to be processed if one of them fails.</p>
  
  <p>So I ended writing 2 private methods:</p>
  
  <pre><code>private Optional&lt;Image&gt; createImage(Path imagePath) {
      try {
          return Optional.of(new Image(imagePath));
      } catch (IOException e) {
          return Optional.empty();
      }
  }
  
  private void write(Image image) {
      try {
          Images.write(image, this.destination);
      } catch (IOException e) {
          // log error
      }
  }
  </code></pre>
  
  <p>createImage() returns an Optional since this seems sensible. However after this my code got really ugly:</p>
  
  <pre><code>public void run() throws IOException {
      Files.list(source)
           .filter(Images::isImage)
           .map(this::createImage)
           .filter(image -&gt; image.isPresent() &amp;&amp; image.get().isProportional(this.height, this.width))
           .map(image -&gt; image.get().resize(this.height, this.width))
           .forEach(this::write);
  }
  </code></pre>
  
  <p>Is there a way to avoid using get() and isPresent() on that code?</p>
  
  <p>Thanks!</p>