简体   繁体   English

Java11中的谓词过滤所有元素

[英]Predicate in Java11 filters all elements

I am moving to use Java11. 我正在使用Java11。 Learning a new method Predicate.not , I found my current code to find only cat family as: 学习一种新的方法Predicate.not ,我发现我目前的代码只找到猫科:

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 马,豹,猫,狗,狮子

What did I do wrong? 我做错了什么?

You seem to be missing the basic De-morgan's laws which states that 你似乎错过了基本的De-morgan法则

!(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

You can write it in that way: 你可以这样写:

List<String> animals = List.of("cat", "leopard", "dog", "lion", "horse");
Set<String> filterCat = animals.stream()
    .filter(Predicate.not("dog"::equals).and(Predicate.not("horse"::equals)))
    .collect(Collectors.toSet());
System.out.println(filterCat);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM