Filter and map a java stream at the same time
<p>I have a list of strings, each of which is represents a date.  I'd like to map this list into a list of DateTime objects; however, if any of the strings are invalid (throws an exception) I'd like to log an error but not add it to the final List. Is there a way to do both the filtering and mapping at the same time?  </p>

<p>This is what I currently have:</p>

<pre><code>List&lt;String&gt; dateStrs = ...;
dateStrs.stream().filter(s -&gt; {
    try {
        dateTimeFormatter.parseDateTime(s);
        return true;
    } catch (Exception e) {
        log.error("Illegal format");
        return false;
    }
}.map(s -&gt; {
    return dateTimeFormatter.parseDateTime(s);
}.collect(...);
</code></pre>

<p>Is there any way to do this so that I don't have to parseDateTime twice for each element?</p>

<p>Thanks</p>