java 8 谓词

In this article, we’ll talk about Java Predicate, which is a Functional Interface. A Functional Interface is one that contains exactly one abstract method.

在本文中,我们将讨论Java谓词,它是一个功能接口 。 功能接口是仅包含一种抽象方法的接口。

Java谓词 (Java Predicate)

Remember predicate from Math class in school? Yeah, something like a function that takes in a value and returns true or false.

还记得学校数学课上的谓词吗? 是的,类似于一个函数,该函数接受一个值并返回true或false。

In Java 8, java.util.function.Predicate was introduced that behaves the same way and can be used as an assignment target in lambda expressions and functional interfaces. The functional method of Predicate is test(Object).

在Java 8 java.util.function.Predicate ,引入了java.util.function.Predicate ,其行为方式相同,可用作lambda表达式和函数接口中的赋值目标。 Predicate的功能方法是test(Object)

Java谓词示例 (Java Predicate Example)

Let’s consider that we have a class Apple:

考虑一下我们有一个Apple类:

package com.journaldev.predicates;public class Apple {private String color;private Double weight;public Apple(String c, Double w) {this.color = c;this.weight = w;}@Overridepublic String toString() {return "Apple{color:" + this.getColor() + ",weight:" + this.getWeight() + "}";}public String getColor() {return color;}public void setColor(String color) {this.color = color;}public Double getWeight() {return weight;}public void setWeight(Double weight) {this.weight = weight;}
}

Now if we have a condition to get the apples whose weight is above 150 grams, we can write a Predicate for it as below:

现在,如果我们有条件获取重量超过150克的苹果,则可以为其编写谓词,如下所示:

package com.journaldev.predicates;import java.util.function.Predicate;public class ApplePredicates {public static Predicate<Apple> isWeightAbove150() {return apple -> apple.getWeight() >= 150;}
}

Now, we can use this predicate in filter(), to filter a list of apples by the condition in this predicate.

现在,我们可以在filter ()使用此谓词,以根据该谓词中的条件来过滤苹果列表。

Let’s add a method filterApples() to the ApplePredicates class:

让我们向ApplePredicates类添加一个方法filterApples()

public static List<Apple> filterApples(List<Apple> apples, Predicate<Apple> predicate) {return apples.stream().filter(predicate).collect(Collectors.toList());
}

We can call this and get the results as below in a main method:

我们可以调用它,并在main方法中获得如下结果:

public static void main(String[] args) {List<Apple> apples = Arrays.asList(new Apple("green", 120.0), new Apple("red", 110.0),new Apple("brown", 150.0), new Apple("green", 160.0), new Apple("red", 122.0));ApplePredicates.filterApples(apples, ApplePredicates.isWeightAbove150()).forEach(System.out::println);
}

Output:

输出:

Apple{color:brown,weight:150.0}
Apple{color:green,weight:160.0}

With java 8 lambda expressions, we can do it simply as below:

使用Java 8 Lambda表达式,我们可以简单地做到如下:

ApplePredicates.filterApples(apples, apple -> {return apple.getWeight() >= 150;
}).forEach(System.out::println);

Or, if we don’t want to define our own method, we can also use the default filter method and write it as:

或者,如果我们不想定义自己的方法,也可以使用默认的filter方法并将其编写为:

apples.stream().filter(apple -> {return apple.getWeight() >= 150;
}).collect(Collectors.toList()).forEach(System.out::println);

Java 8谓词方法 (Java 8 Predicate Methods)

Let’s now go through the methods available for Predicate:

现在让我们看一下Predicate可用的方法:

  1. default Predicate and(Predicate other) (default Predicate and(Predicate other))

    Returns a composed predicate that represents a logical AND of two predicates. When evaluating the composed predicate, if this predicate is false, then the other predicate is not evaluated.

    To understand this, let’s add another predicate in the ApplePredicates class:

    public static Predicate<Apple> isColorGreen() {return apple -> apple.getColor().equals("green");
    }

    Now we can apply the and() function if we want to get a predicate for apple to be green and weight above or equal to 150 grams.

    This will give the following output:

    Apple{color:green,weight:160.0}

    Similarly, we have or() method to do the short-circuiting, logical ORing of two predicates.

    返回表示两个谓词的逻辑与的组合谓词。 在评估组合谓词时,如果该谓词为假,则不会评估另一个谓词。

    为了理解这一点,让我们在ApplePredicates类中添加另一个谓词:

    现在and()如果我们要使苹果成为绿色且重量大于或等于150克的谓词,则可以应用and()函数。

    Predicate<Apple> andPredicate = ApplePredicates.isColorGreen().and(ApplePredicates.isWeightAbove150());
    apples.stream().filter(andPredicate).forEach(System.out::println);

    这将给出以下输出:

    同样,我们有or()方法对两个谓词进行短路,逻辑或运算。

  2. default Predicate negate() (default Predicate negate())

    Returns a predicate that represents the logical negation of this predicate.

    Let’s say we want the Predicate to get apples that are not green. We already have one predicate that checks for Apple to be green, so we can negate it.

    Predicate<Apple> negateExample = ApplePredicates.isColorGreen().negate();
    apples.stream().filter(negateExample).forEach(System.out::println);

    The output will be:

    返回表示此谓词逻辑否定的谓词。

    假设我们希望谓词获得不是绿色的苹果。 我们已经有一个判断苹果是否为绿色的谓词,因此我们可以否定它。

    Predicate<Apple> negateExample = ApplePredicates.isColorGreen().negate();
    apples.stream().filter(negateExample).forEach(System.out::println);

    输出将是:

  3. boolean test(T t) (boolean test(T t))

    Evaluates this predicate for the given argument. In our case, we can pass in an Apple object to check if this predicate returns true or false for that apple.

    Apple testApple = new Apple("green", 120.0);
    System.out.println(ApplePredicates.isColorGreen().test(testApple));
    System.out.println(ApplePredicates.isWeightAbove150().test(testApple));

    Output:

    评估给定参数的谓词。 在我们的例子中,我们可以传入一个Apple对象,以检查该谓词对于该苹果返回的是true还是false。

    Apple testApple = new Apple("green", 120.0);
    System.out.println(ApplePredicates.isColorGreen().test(testApple));
    System.out.println(ApplePredicates.isWeightAbove150().test(testApple));

    输出:

  4. static Predicate isEqual(Object targetRef) (static Predicate isEqual(Object targetRef))

    Returns a predicate that tests if two arguments are equal according to Objects.equals() method.

    Consider we have overridden the equals() method for Apple class:

    @Override
    public boolean equals(Object obj) {Apple apple = (Apple) obj;if (this.getColor().equals(apple.getColor()) && this.getWeight().equals(apple.getWeight())) {return true;}return false;
    }

    Now, let’s say we have an Apple, which has standard color and weight. Then we can get a Predicate, that will test if the given apple is standard or not.

    This will output:

    false
    true

    返回一个谓词,该谓词根据Objects.equals()方法测试两个参数是否相等。

    考虑我们已经为Apple类重写了equals()方法:

    现在,假设我们有一个具有标准颜色和重量的苹果。 然后我们可以获得一个谓词,它将测试给定的苹果是否为标准苹果。

    Predicate<Apple> standardApplePredicate = Predicate.isEqual(new Apple("red", 150.0));Apple testApple = new Apple("green", 120.0);
    System.out.println(standardApplePredicate.test(testApple));
    System.out.println(standardApplePredicate.test(new Apple("red", 150.0)));

    这将输出:

That’s it for Java Predicate functional interface.

Java谓词功能接口就是这样。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/17072/java-predicate

java 8 谓词

java 8 谓词_Java谓词– Java 8谓词相关推荐

  1. java直接量_Java教程:Java直接量(字面量)

    Java教程直接量是指在程序中通过源代码直接给出的值,例如在int a = 5;代码中,为变量 a 所分配的初始值 5 就是一个直接量. 直接量的类型 并不是所有的数据类型都可以指定直接量,能指定直接 ...

  2. java native 接口_Java本地接口--Java Native Interface (JNI)

    一.方法介绍 java native方法是指本地方法,当在方法中调用一些不是由java语言写的代码或者在方法中用java语言直接操纵计算机硬件时要声明为native方法. java中,通过JNI(Ja ...

  3. eclipse java web乱码_JAVA and JAVA WEB with TOMCAT and ECLIPSE 学习过程中遇到的字符乱码问题及解决方法汇总(随时补充)...

    JAVA语言具有跨平台,unicode字符集编码的特点. 但是在开发过程中处理数据时涉及到的字符编码问题零零散散,尤其是处理中文字符时一不留神就可能出现一堆奇奇怪怪的符号,俗称乱码. 对于乱码,究其原 ...

  4. java序列化 反序列化_Java序列化– Java序列化

    java序列化 反序列化 Serialization in Java was introduced in JDK 1.1 and it is one of the important feature ...

  5. java获取屏幕截图_java 利用java运行时的方法得到当前屏幕截图的方法

    将截屏图片保存到本地路径: package com.test; import java.awt.AWTException; import java.awt.Dimension; import java ...

  6. java 平台无关_Java | 为什么 Java 实现了平台无关性?

    前言从最初学习Java开始,我们就知道Java的口号是:"一次编写,到处运行".没有了平台的束缚,使得我们再编写Java时并不需要(那么)关心将来运行程序的平台. 那么,Java是 ...

  7. java循环变量_Java初学——Java入门变量 常量选择循环结构

    一.初识java 1.jdk的介绍 下载安装jdk 安装后会存在默认的安装路径 bin 目录:存放编译,运行 Java 程序的可执行文件 lib 目录:存放 Java 的类库文件 jre 目录:存放 ...

  8. java 父类 超类_Java超类-java.lang.object

    Java是面向对象的,Object是所有对象的超类(不是继承,也不是实现接口) Object类是所有Java类的祖先.每个类都使用 Object 作为超类.所有对象(包括数组)都实现这个类的方法. 如 ...

  9. java 参数返回_Java基础---Java中带参数返回值方法的使用(四十)

    Java 中带参带返回值方法的使用 如果方法既包含参数,又带有返回值,我们称为带参带返回值的方法. 例如:下面的代码,定义了一个 show 方法,带有一个参数 name ,方法执行后返回一个 Stri ...

  10. 下载不了java应用程序_Java 7u45 - java webstart不会下载我的jar并执行应用程序,除非我显示java控制台...

    首先,对不起我的英语,这不是我的母语. 我的环境有: - jre 1.5.0_12(二进制) - jre 1.6.0_17(默认jre) - jre 1.7.0_45(二进制) 我有两种方法可以通过J ...

最新文章

  1. 菜鸟实时数仓技术架构演进
  2. TensorFlow object detection api------ssd_mobilenet使用
  3. 设置elf文件链接库的路径
  4. linux shell脚本学习xargs命令使用详解
  5. AppVerifier的功能和原理
  6. linux查看网卡连接哪个cpu,Linux查看CPU/内存/网卡/操作系统信息
  7. Linux中chown和chmod的区别和用法
  8. EXP-00056遇到Oracle错误1455问题解决办法
  9. 微信小程序在组件中关闭小程序
  10. k系列服务器,Nvidia开普勒K4000、K2000、K2000D、K600四款Kepler架构Quadro显卡专业卡全新登场...
  11. 实时监控网页变化,并增加多种提示信息
  12. 【破解APP抓包限制】Xposed+JustTrustMe关闭SSL证书验证!
  13. 为什么要架设移动基站
  14. 如何在Win10不同设备之间同步便签
  15. 基于python 的电影票房可视化系统
  16. unet预测图片全黑/全灰解决方案(keras)
  17. vim autoformat php,Linux Vim代码格式化/美化插件vim-autoformat安装
  18. SpringBoot入门:项目下载,依赖,启动
  19. 吹爆这个 pandas GUI 神器,自动转代码!
  20. ruoyi 前后端分离 增加手机号登录

热门文章

  1. 【POJ】【3164】Commond Network
  2. [转载] python匿名(lambda)函数
  3. 阿里巴巴矢量图标库(Iconfont)-利于UI和前端的搭配
  4. JSP学习 三大指令、九个内置对象、JavaBean、EL表达式
  5. BZOJ 4034 树上操作
  6. 27_线程池_线程池实现原理
  7. Qt Qwdget 汽车仪表知识点拆解2 图像放大
  8. R 学习笔记《五》 R语言初学者指南--第二章总结
  9. magento smtp设置
  10. 分页组件change_javascript原生瀑布流+图片懒加载组件