Use lambda filter if element is not null otherwise ignore filter

Angelina :

I have a lambda that currently returns 1st row where date matches passed in date, by using RecordNumber.

ProList 1
    RecordNumber 1
    ProEffectiveDate NULL

ProList 2
    RecordNumber 2
    ProEffectiveDate 2019-03-01

ProList 3
    RecordNumber 3
    ProEffectiveDate 2019-03-01

Here is my current code:

Predicate<ProList> filteredRow = 
                    it->it.getProEffectiveDate()!=null &&
                    it.getProEffectiveDate().equals(passedInDate);

final ProList minFilteredRow = ProList()
    .stream()
    .filter(filteredRow)                               
    .min(Comparator.comparing(ProList::getRecordNumber))
    .orElse(null);

Now, I have to add functionality for if ProEffectiveDate is null to simply return first row from the list. When ProEffectiveDate is null, how do I ignore this filter?

Naman :

Seems like your logic required is to check if any of the ProEffectiveDate is null just return the first element of the list, based on that you could do a check as :

ProList minFilteredRow;
if (proLists.stream().anyMatch(a -> a.getProEffectiveDate() == null)) {
    minFilteredRow = proLists.get(0);
} else {
    minFilteredRow = proLists.stream()
            .filter(filteredRow)
            .min(Comparator.comparing(ProList::getRecordNumber))
            .orElse(null);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=70370&siteId=1