JDK 8 -- Predicate接口

  • 抽象方法

    boolean test(T t);
    
  • 该方法对传入的参数进行验证,满足条件返回true,否则返回false。

  • 使用Lambda表达式实现Predicate接口

      Predicate predicate = e -> "mattie".equals(e);
      predicate.test("mattie"); //true
      predicate.test("hello"); //false
  • Predicate接口与BiFunction接口的结合使用

    public static void main(String[] args) {
        List names = Arrays.asList("ted", "mattie", "hello", "world");
        //找出names中包含字母e的元素
         List result = getNameContainingCharacter("e", names, (t, u) -> {
              return u.stream().filter(name -> name.contains(t)).collect(Collectors.toList());
         });
    }
    
    public static List getNameContainingCharacter(String c, List names, BiFunction, List> biFunc) {
        return biFunc.apply(c, names);
    }
    
  • 用Predicate接口传递`调用行为

  public static void main(String[] args) {
          List list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
          PredicateDemo instance = new PredicateDemo();
          instance.conditionFilter(list, e -> {return e > 5;});
          instance.conditionFilter(list, e -> e % 2 == 0);
          instance.conditionFilter(list, e -> true);//打印所有元素
   }
  public void conditionFilter(List list, Predicate predicate) {
      list.forEach(e -> {
        if (predicate.test(e)) {
            System.out.println(e);
        }
      });
  }
  • and, or, negate方法
        Predicate p = e -> e > 5;
        //取反
        instance.conditionFilter(list, p.negate()); // 5 6 7 8 9 10

        //and
        instance.conditionFilter(list, p.and(e -> e < 9));//6 7 8

        //or
        instance.conditionFilter(list, p.or(e -> e < 4));//1 2 3 6 7 8 9 10
  • isEqual方法说明

      static  Predicate isEqual(Object targetRef) {
          return (null == targetRef)
                  ? Objects::isNull   //接口的函数引用实现,满足test方法签名的要求:接受一个参数,返回boolean值
                  : object -> targetRef.equals(object); //接口的lambda表达式实现,object就是test(T t)方法的参数t
      }

你可能感兴趣的:(JDK 8 -- Predicate接口)