Predicate 接口说明

  1. /*
  2. * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
  3. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  4. */
  5. package java.util.function;
  6.  
  7. import java.util.Objects;
  8.  
  9. /**
  10. * Represents a predicate (boolean-valued function) of one argument.
  11. *
  12. * <p>This is a <a href="package-summary.html">functional interface</a>
  13. * whose functional method is {@link #test(Object)}.
  14. *
  15. * @param <T> the type of the input to the predicate
  16. *
  17. * @since 1.8
  18. */
  19. @FunctionalInterface
  20. public interface Predicate<T> {
  21.  
  22. /**
  23. * Evaluates this predicate on the given argument.
  24. *
  25. * @param t the input argument
  26. * @return {@code true} if the input argument matches the predicate,
  27. * otherwise {@code false}
  28. */
  29. boolean test(T t);
  30.  
  31. /**
  32. * Returns a composed predicate that represents a short-circuiting logical
  33. * AND of this predicate and another. When evaluating the composed
  34. * predicate, if this predicate is {@code false}, then the {@code other}
  35. * predicate is not evaluated.
  36. *
  37. * <p>Any exceptions thrown during evaluation of either predicate are relayed
  38. * to the caller; if evaluation of this predicate throws an exception, the
  39. * {@code other} predicate will not be evaluated.
  40. *
  41. * @param other a predicate that will be logically-ANDed with this
  42. * predicate
  43. * @return a composed predicate that represents the short-circuiting logical
  44. * AND of this predicate and the {@code other} predicate
  45. * @throws NullPointerException if other is null
  46. */
  47. default Predicate<T> and(Predicate<? super T> other) {
  48. Objects.requireNonNull(other);
  49. return (t) -> test(t) && other.test(t);
  50. }
  51.  
  52. /**
  53. * Returns a predicate that represents the logical negation of this
  54. * predicate.
  55. *
  56. * @return a predicate that represents the logical negation of this
  57. * predicate
  58. */
  59. default Predicate<T> negate() {
  60. return (t) -> !test(t);
  61. }
  62.  
  63. /**
  64. * Returns a composed predicate that represents a short-circuiting logical
  65. * OR of this predicate and another. When evaluating the composed
  66. * predicate, if this predicate is {@code true}, then the {@code other}
  67. * predicate is not evaluated.
  68. *
  69. * <p>Any exceptions thrown during evaluation of either predicate are relayed
  70. * to the caller; if evaluation of this predicate throws an exception, the
  71. * {@code other} predicate will not be evaluated.
  72. *
  73. * @param other a predicate that will be logically-ORed with this
  74. * predicate
  75. * @return a composed predicate that represents the short-circuiting logical
  76. * OR of this predicate and the {@code other} predicate
  77. * @throws NullPointerException if other is null
  78. */
  79. default Predicate<T> or(Predicate<? super T> other) {
  80. Objects.requireNonNull(other);
  81. return (t) -> test(t) || other.test(t);
  82. }
  83.  
  84. /**
  85. * Returns a predicate that tests if two arguments are equal according
  86. * to {@link Objects#equals(Object, Object)}.
  87. *
  88. * @param <T> the type of arguments to the predicate
  89. * @param targetRef the object reference with which to compare for equality,
  90. * which may be {@code null}
  91. * @return a predicate that tests if two arguments are equal according
  92. * to {@link Objects#equals(Object, Object)}
  93. */
  94. static <T> Predicate<T> isEqual(Object targetRef) {
  95. return (null == targetRef)
  96. ? Objects::isNull
  97. : object -> targetRef.equals(object);
  98. }
  99. }

根据接口说明,Predicate 提供的为逻辑判断操作,即断言。

静态方法isEqual:判断是否相等,并返回一个Predicate对象

调用:Predicate.isEqual(Object1).test(Object2)

含义:使用Object1的equals方法判断Object2是否与其相等。

默认方法and,or,negate:分别代表逻辑判断与、或、非并都返回一个Predicate对象

调用:Predicate1.and(Predicate2).test(Object)

含义:判断Object对象是否满足Predicate1 && Predicate2

方法test:按照给定的Predicate条件进行逻辑判断。

  1. package org.htsg;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import java.util.Objects;
  6. import java.util.function.Predicate;
  7.  
  8. /**
  9. * @author HTSG
  10. */
  11. public class PredicateTest {
  12. public static void main(String[] args) {
  13. // 添加十个学生
  14. List<Student> studentList = new ArrayList<>(10);
  15. for (int i = 0; i < 10; i++) {
  16. studentList.add(new Student("student" + i, 10 + i));
  17. }
  18. // 获取年龄大于15的学生
  19. // [Student{name='student6', age=16}, Student{name='student7', age=17}, Student{name='student8', age=18}, Student{name='student9', age=19}]
  20. List<Student> filteredStudents = test(studentList, PredicateTest::filterAge1);
  21. System.out.println(filteredStudents);
  22. // 获取年龄大于15并且名字叫 "student7" 的学生
  23. // [Student{name='student7', age=17}]
  24. filteredStudents = and(studentList, PredicateTest::filterAge1, PredicateTest::filterName);
  25. System.out.println(filteredStudents);
  26. // 获取年龄不大于15的学生
  27. // [Student{name='student0', age=10}, Student{name='student1', age=11}, Student{name='student2', age=12}, Student{name='student3', age=13}, Student{name='student4', age=14}, Student{name='student5', age=15}]
  28. filteredStudents = negate(studentList, PredicateTest::filterAge1);
  29. System.out.println(filteredStudents);
  30. // 获取年龄不大于15或名字叫 "student7" 的学生
  31. // [Student{name='student0', age=10}, Student{name='student1', age=11}, Student{name='student2', age=12}, Student{name='student3', age=13}, Student{name='student4', age=14}, Student{name='student5', age=15}, Student{name='student7', age=17}]
  32. filteredStudents = or(studentList, PredicateTest::filterAge2, PredicateTest::filterName);
  33. System.out.println(filteredStudents);
  34. // 获取和目标学生属性值相同的学生列表
  35. // [Student{name='student1', age=11}]
  36. filteredStudents = isEqual(studentList, new Student("student1", 11));
  37. System.out.println(filteredStudents);
  38.  
  39. }
  40.  
  41. public static boolean filterAge1(Student student) {
  42. return student.getAge() > 15;
  43. }
  44.  
  45. public static boolean filterAge2(Student student) {
  46. return student.getAge() <= 15;
  47. }
  48.  
  49. public static boolean filterName(Student student) {
  50. return "student7".equals(student.getName());
  51. }
  52.  
  53. public static List<Student> test(List<Student> students, Predicate<Student> pre) {
  54. List<Student> result = new ArrayList<>(10);
  55. for (Student student : students) {
  56. if (pre.test(student)) {
  57. result.add(student);
  58. }
  59. }
  60. return result;
  61. }
  62.  
  63. public static List<Student> and(List<Student> students, Predicate<Student> pre1, Predicate<Student> pre2) {
  64. List<Student> result = new ArrayList<>(10);
  65. for (Student student : students) {
  66. if (pre1.and(pre2).test(student)) {
  67. result.add(student);
  68. }
  69. }
  70. return result;
  71. }
  72.  
  73. public static List<Student> negate(List<Student> students, Predicate<Student> pre) {
  74. List<Student> result = new ArrayList<>(10);
  75. for (Student student : students) {
  76. if (pre.negate().test(student)) {
  77. result.add(student);
  78. }
  79. }
  80. return result;
  81. }
  82.  
  83. public static List<Student> or(List<Student> students, Predicate<Student> pre1, Predicate<Student> pre2) {
  84. List<Student> result = new ArrayList<>(10);
  85. for (Student student : students) {
  86. if (pre1.or(pre2).test(student)) {
  87. result.add(student);
  88. }
  89. }
  90. return result;
  91. }
  92.  
  93. public static List<Student> isEqual(List<Student> students, Student student) {
  94. List<Student> result = new ArrayList<>(10);
  95. for (Student studentTemp : students) {
  96. if (Predicate.isEqual(student).test(studentTemp)) {
  97. result.add(studentTemp);
  98. }
  99. }
  100. return result;
  101. }
  102.  
  103. // 创建静态内部类
  104. public static class Student {
  105. private String name;
  106. private int age;
  107.  
  108. public Student() {
  109. }
  110.  
  111. public Student(String name, int age) {
  112. this.name = name;
  113. this.age = age;
  114. }
  115.  
  116. public String getName() {
  117. return name;
  118. }
  119.  
  120. public void setName(String name) {
  121. this.name = name;
  122. }
  123.  
  124. public int getAge() {
  125. return age;
  126. }
  127.  
  128. public void setAge(int age) {
  129. this.age = age;
  130. }
  131.  
  132. @Override
  133. public String toString() {
  134. return "Student{" +
  135. "name='" + name + '\'' +
  136. ", age=" + age +
  137. '}';
  138. }
  139.  
  140. @Override
  141. public boolean equals(Object o) {
  142. if (this == o) {
  143. return true;
  144. }
  145. if (o == null || getClass() != o.getClass()) {
  146. return false;
  147. }
  148. Student student = (Student) o;
  149. return age == student.age &&
  150. Objects.equals(name, student.name);
  151. }
  152. }
  153. }

Java Predicate的更多相关文章

  1. J2SE 8的Lambda --- functions

    functions //1. Runnable 输入参数:无 返回类型void new Thread(() -> System.out.println("In Java8!" ...

  2. Spark案例分析

    一.需求:计算网页访问量前三名 import org.apache.spark.rdd.RDD import org.apache.spark.{SparkConf, SparkContext} /* ...

  3. lambda -- Java 8 find first element by predicate

        Java 8 find first element by predicate up vote6down votefavorite I've just started playing with ...

  4. Java 8 基础教程 - Predicate

    在Java 8中,Predicate是一个函数式接口,可以被应用于lambda表达式和方法引用.其抽象方法非常简单: /** * Evaluates this predicate on the giv ...

  5. Java 8 新特性:4-断言(Predicate)接口

    (原) 这个接口主要用于判断,先看看它的实现,说明,再给个例子. /* * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All ri ...

  6. 一点一点看JDK源码(五)java.util.ArrayList 后篇之removeIf与Predicate

    一点一点看JDK源码(五)java.util.ArrayList 后篇之removeIf与Predicate liuyuhang原创,未经允许禁止转载 本文举例使用的是JDK8的API 目录:一点一点 ...

  7. java代码之美(13)--- Predicate详解

    java代码之美(13)--- Predicate详解 遇到Predicate是自己在自定义Mybatis拦截器的时候,在拦截器中我们是通过反射机制获取对象的所有属性,再查看这些属性上是否有我们自定义 ...

  8. Java常用函数式接口--Predicate接口使用案例

    Java常用函数式接口--Predicate接口使用案例 该方法可以使用and来优化: 调用:

  9. java 8中 predicate chain的使用

    目录 简介 基本使用 使用多个Filter 使用复合Predicate 组合Predicate Predicate的集合操作 总结 java 8中 predicate chain的使用 简介 Pred ...

随机推荐

  1. 2018-10-10-weekly

    Algorithm 字典序排数 What 给定一个整数n,返回从1到n的字典顺序,例如,给定 n =13,返回 [1,10,11,12,13,2,3,4,5,6,7,8,9] ,尽可能的优化算法的时间 ...

  2. 微信 ios img图片不显示问题

    使用div标签,将图片作为background .

  3. JavaWeb(四):JDBC

    数据持久化(persistence) 把数据保存到可掉电式存储设备中以供之后使用. 大多数情况下,特别是企业级应用,数据持久化意味着将内存中的数据保存到硬盘上加以”固化”,而持久化的实现过程大多通过各 ...

  4. CGfsb

    这里补充一下%n是代表向参数赋值打印的字符个数 例如printf("AAAA%n",&a); 代表的是向a写入4 printf("AAAA%1n", & ...

  5. Apache HttpClient之fluent API的使用

    该方法为Apache HttpClient 4.5以上的版本支持,在官网有明确的说明. 对比以前的方式,其优点是代码更简洁,同时为线程安全的.仅举一个最简单的post栗子 JAR包信息: <de ...

  6. 按照MySQL

    转载自:https://mp.weixin.qq.com/s?__biz=MzIwNzk0NjE1MQ==&mid=2247484200&idx=1&sn=6eed12242c ...

  7. PHP截取字符串函数,根据dede修改而来

    dede中,有一个函数function cn_substr_utf8($str, $length, $start=0) 但测试时,并不如我所想的一样,可能是因为个人使用习惯吧.比如,字符串为数字或字母 ...

  8. BZOJ 1597: [Usaco2008 Mar]土地购买 动态规划 + 斜率优化

    Code: #include<bits/stdc++.h> #define maxn 1000000 #define ll long long #define x(i) (b[i+1]) ...

  9. 【2019ICPC西安邀请赛】J.And And And(点分治,贡献)

    题意:给定一棵n个点带边权的树,定义每条路径的值为路径上边权的异或和 如果一条路径的值为0,其对答案的贡献为所有包含这条路径的路径条数 求答案膜1e9+7 n<=1e5,0<=边权< ...

  10. window安装rsync客户端和服务端

    原文地址: https://www.cnblogs.com/janas/p/3321087.html 下载地址: https://linux.linuxidc.com/index.php?folder ...