How do I return a value from a lambda within the method I want to return on?
Originally, I had this:
myCollection.forEach(item -> {
try {
doSomething(item);
} catch (Exception e) {
return "There was a problem doing something: " + e.getMessage();
}
});
But my intent was to return on the method containing all this code, not return on just the lambda. So, I ended up having to do this:
String error = "";
myCollection.stream().filter(item -> {
try {
doSomething(item);
return true;
} catch (Exception e) {
error = "There was a problem doing something: " + e.getMessage();
}
return false;
});
if (!error.isEmpty()) {
return error;
}
But this can't be the best way. What's the Java 8 functional, elegant way to do this?