You must continue filtering the Java stream when the card throws an exception after the filter and findFirst

I have this code:

return myList
    .stream()
    .filter(Objects::nonNull)
    .filter(listItem -> {
        try {
            return listItem.matchesCondition();
        } catch (Exception e) {
            // log error
            return false;
        }
    })
    .findFirst()
    .map(listItem -> {
        try {
            return listItem.getResult();
        } catch (Exception e) {

            // IF THIS HAPPENS, HOW CAN WE ADVANCE TO THE NEXT ITEM IN THE STREAM.
            // I'M ASSUMING WE CAN NOT SINCE THE STREAM WAS TERMINATED BY findFirst.
            // BUT HOW CAN I WRITE THIS IN A DIFFERENT WAY TO ACHIEVE THAT BEHAVIOR?

            // log error
            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) {

        // SWALLOW THE EXCEPTION SO THE NEXT ITEM IS TESTED

        // log error
    }
}

return Optional.empty();
+4
source share
1 answer

findFirst , ( ) , "" .

return myList
    .stream()
    .filter(Objects::nonNull)
    .filter( ... )
    .map( ... ) // returns null on Exception, so filter again
    .filter(Objects::nonNull)
    .findFirst()
+3

Source: https://habr.com/ru/post/1679929/


All Articles