membersound membersound - 6 months ago 9
Java Question

How to iterate a stream even if exceptions are thrown?

stream.map(obj -> doMap(obj)).collect(Collectors.toList());

private String doMap(Object obj) {
if (objectIsInvalid) {
throw new ParseException("Object could not be parsed");
}
}


Problem: how can I throw the exception and make the stream iteration know that it should not break the whole iteration, but continue with the next element (and eventually log failed objects)?

Answer

Without an exception you can work with Optionals:

stream.map(obj -> doMap(obj)).filter(obj -> obj.isPresent()).collect(Collectors.toList());

private Optional<String> doMap(Object obj) {
   if (objectIsInvalid) {
    return Optional.empty();
   }
}