5

Hello how can I do in java 8 (I know its already in java 11) the opposite to not filter for this

filter(date -> date.isEqual(today) && repository.isDateExist(date))

I can write like so

filter(date -> !date.isEqual(today) || !repository.isDateExist(date))

but its hard to read

Naman
  • 27,789
  • 26
  • 218
  • 353
Anton Kolosok
  • 482
  • 9
  • 24

2 Answers2

1

You can use Predicate's negate() method, but that would require casting the lambda expression to the Predicate type. Otherwise the compiler cannot infer the type.

filter(((Predicate<Date>)(date -> date.isEqual(today) && repository.isDateExist(date))).negate())

Or just assign the Predicate to a variable before negating it:

Predicate<Date> pred = date -> date.isEqual(today) && repository.isDateExist(date);
filter(pred.negate())
Eran
  • 387,369
  • 54
  • 702
  • 768
1

With a condition like

filter(date -> date.isEqual(today) && repository.isDateExist(date))

the term repository.isDateExist(date) is only evaluated when date has been proven to be equal to today, so its outcome is the same as repository.isDateExist(today), which doesn’t change during the entire stream operation. Hence, there is no reason to repeatedly check that.

So the preferable variant would be

final boolean todayExist = repository.isDateExist(today);
…
filter(todayExist? today::isEqual: date -> false)

The negation would be

final boolean todayExist = repository.isDateExist(today);
…
filter(todayExist? date -> true: date -> !date.isEqual(today))

though for this you might consider not applying a filter at all when todayExist is true.

Holger
  • 285,553
  • 42
  • 434
  • 765