Q:

Stream filter for Date

I have a list of custom objects, which have a String field to store the date.
I need to write a filter to fetch the list of custom objects based on the condition: if days between custom object date and current date is equals to 4 then return the satified object in list.
I tried to parse the custom object string date to ZonedDateTime in filter. But it's expecting the try/catch block. How to handle this case?
Code:
list.stream().filter(ChronoUnit.DAYS.between(currDate,
    ZonedDateTime.ofInstant((df.parse(stringdate).toInstant(),ZoneId.of("UTC"))) == 4)

A:

You can use try/catch in lambdas:
list.stream().filter(stringdate -> {
        try {
            return ChronoUnit.DAYS.between(currDate,
                    ZonedDateTime.ofInstant(df.parse(stringdate).toInstant(),
                                            ZoneId.of("UTC"))) == 4;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return false;
    }).collect(...);

What do to in case of an exception is up to you of course, the return false in this code causes the element to be filtered out. You can also have another method that does the parsing and exception handling which you call from the lambda.

