JDK 8 -- Predicate接口

作者: ted005 | 来源:发表于2017-01-18 17:09 被阅读241次
  • 抽象方法

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

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

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

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

  public static void main(String[] args) {
          List<Integer> 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<Integer> list, Predicate<Integer> predicate) {
      list.forEach(e -> {
        if (predicate.test(e)) {
            System.out.println(e);
        }
      });
  }
  • and, or, negate方法
        Predicate<Integer> 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 <T> Predicate<T> isEqual(Object targetRef) {
          return (null == targetRef)
                  ? Objects::isNull   //接口的函数引用实现,满足test方法签名的要求:接受一个参数,返回boolean值
                  : object -> targetRef.equals(object); //接口的lambda表达式实现,object就是test(T t)方法的参数t
      }

相关文章

网友评论

    本文标题:JDK 8 -- Predicate接口

    本文链接:https://www.haomeiwen.com/subject/nchbbttx.html