I often check if a collection contains an element during stream operations and I write code like this:
Set<String> users = ...
Set<String> unemployed = ...
users.stream().filter(unemployedUsers::contains)
But I also need to check NOT condition, then I have to write something like this:
users.stream().filter(user -> !unemployedUsers.contains(user))
which looks less readable and a bit ugly.
It would be great if I could replace it with something like this:
users.stream().filter(not(unemployedUsers::contains))
But I haven't found any API in standard lib that allows this.
Q: How can I replace lambda expression with method reference when I need to check NOT condition? Or is there any other way that would do the same but in more elegant way?
UPDATE: This question duplicates "How to negate a method reference predicate". However is more about how to write NOT operation in more readable/elegant way.
I can write custom code like this
Predicate<String> not(Predicate<String> predicate) {
return predicate.negate();
}
And use the construction with not(unemployedUsers::contains)
, but there might be someone who solves this problem in better way.