title: Java 8 streams map, keep nulls as null
body: <p>I have this piece of code:</p>
  
  <pre><code>public LatLng[] locationDtoListToLatLngArray(List&lt;LocationDto&gt; locationDtoList) {
      return locationDtoList.stream()
              .map(locationDto -&gt; new LatLng(locationDto.getLatitude(), locationDto.getLongitude()))
              .toArray(LatLng[]::new);
  }
  </code></pre>
  
  <p>but is crashing if <code>locationDto</code> is <code>null</code> inside <code>.map</code></p>
  
  <p>I fixed it doing this:</p>
  
  <pre><code>public LatLng[] locationDtoListToLatLngArray(List&lt;LocationDto&gt; locationDtoList) {
      return locationDtoList.stream()
              .map(locationDto -&gt; locationDto == null ? null : new LatLng(locationDto.getLatitude(), locationDto.getLongitude()))
              .toArray(LatLng[]::new);
  }
  </code></pre>
  
  <p>but I want to know if there is a better approach (without checking if <code>locationDto == null</code>)</p>
  
  <p>Please note that, if <code>locationDto == null</code>, I want to keep the <code>null</code>, so filter is not an option :)</p>
  
  <p>Thanks</p>
  
  <p>EDIT: I know that the problem is accessing a null object, I just want to know is if there is some function like <code>.map()</code>, that do what I need, <code>.mapKeepingNulls()</code>, something like that.</p>
  
  <p>EDIT 2: I ended up doing this:</p>
  
  <pre><code>public LatLng[] locationDtoListToLatLngArray(List&lt;LocationDto&gt; locationDtoList) {
      return locationDtoList.stream()
              .map(this::locationDtoToLatLng)
              .toArray(LatLng[]::new);
  }
  
  private LatLng locationDtoToLatLng(LocationDto locationDto) {
      if (locationDto == null) {
          return null;
      }
      return new LatLng(locationDto.getLatitude(), locationDto.getLongitude());
  }
  </code></pre>