Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Predicate in Java11 filters all elements

I am moving to use Java11. Learning a new method Predicate.not, I found my current code to find only cat family as:

List<String> animals = List.of("cat", "leopard", "dog", "lion", "horse");
Predicate<String> cats = a -> !a.equals("dog") && !a.equals("horse");
Set<String> filterCat = animals.stream().filter(cats).collect(Collectors.toSet());
System.out.println(filterCat);

output is :

leopard, cat, lion

Now I am trying to use the new method and the output is coming incorrect. How do I correct it? What did I do wrong?

My later code:

Predicate<String> updatedCatFilter = Predicate.not(a -> a.equals("dog") && a.equals("horse"));
Set<String> catFamily = animals.stream().filter(updatedCatFilter).collect(Collectors.toSet());
System.out.println(filterCat);

But this outputs all my list now.

horse, leopard, cat, dog, lion

like image 299
Mani Avatar asked Jan 06 '19 06:01

Mani


People also ask

Is filter a predicate?

filter() accepts predicate as argument.

What is predicate in lambda expression?

Predicate<T> is a generic functional interface that represents a single argument function that returns a boolean value (true or false). This interface available in java. util. function package and contains a test(T t) method that evaluates the predicate of a given argument.

What is a predicate method?

The predicate is a predefined functional interface in Java defined in the java. util. Function package. It helps with manageability of code, aids in unit-testing, and provides various handy functions.

What is the predicate in Java 8?

Java Predicate Interface It is a functional interface which represents a predicate (boolean-valued function) of one argument. It is defined in the java. util. function package and contains test() a functional method.


1 Answers

What did I do wrong?

You seem to be missing the basic De-morgan's laws which states that

!(a || b) == !a && !b

and

!(a && b) == !a || !b

How do I correct it?

So you should change your code to use

Predicate.not(a -> a.equals("dog") || a.equals("horse")); // !(a || b)

which shall be equivalent to your existing code

Predicate<String> cats = a -> !a.equals("dog") && !a.equals("horse");

that can also be looked upon as:

Predicate<String> notDog = a -> !a.equals("dog");
Predicate<String> notHorse =  a -> !a.equals("horse");
Predicate<String> cats = notDog.and(notHorse); // !a && !b
like image 82
Naman Avatar answered Sep 18 '22 20:09

Naman