I have this code:
return myList
.stream()
.filter(Objects::nonNull)
.filter(listItem -> {
try {
return listItem.matchesCondition();
} catch (Exception e) {
return false;
}
})
.findFirst()
.map(listItem -> {
try {
return listItem.getResult();
} catch (Exception e) {
return null;
}
});
The problem is that if the first matching listItem throws an exception in the map function, an empty Optional is returned.
But instead, I want to continue testing the remaining items in the list and try to match the next one that matches the filter.
How can I do this with threads and lambdas?
I can convert this more imperative code, but would like to find a functional solution.
for (MyListItem myList : listItem) {
try {
if (listItem.matchesCondition()) {
return Optional.of(listItem.getResult());
}
} catch (Exception e) {
}
}
return Optional.empty();
source
share