暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Java新特性解读JDK8之函数式接口Predicate

227decision 2020-01-18
612
Predicate作为断言型接口:有入参,返回值类型是boolean

Predicate源码

    package java.util.function;


    import java.util.Objects;


    /**
    * Represents a predicate (boolean-valued function) of one argument.
    *
    * <p>This is a <a href="package-summary.html">functional interface</a>
    * whose functional method is {@link #test(Object)}.
    *
    * @param <T> the type of the input to the predicate
    *
    * @since 1.8
    */
    @FunctionalInterface
    public interface Predicate<T> {


    /**
    * Evaluates this predicate on the given argument.
    *
    * @param t the input argument
    * @return {@code true} if the input argument matches the predicate,
    * otherwise {@code false}
    */
    boolean test(T t);
    }
    复制

    Predicate使用

      package com.example.functionalinterfacedemo;


      import java.util.ArrayList;
      import java.util.Arrays;
      import java.util.List;
      import java.util.function.Predicate;


      public class PredicateDemo {
      public static void main(String[] args) {
      List<Integer> asList = Arrays.asList(1,2,3,4,5,6,7,8,9);
      List<Integer> list = test(asList, obj->obj.intValue()>5);
      System.out.println(list);
      }


      /**
      *
      * @param list 接受参数
      * @param predicate 定义函数
      * @return 满足一定条件的数据
      */
      public static List<Integer> test(List<Integer> list,Predicate<Integer> predicate){
      List<Integer> list2=new ArrayList<Integer>();
      for(Integer integer :list ){
      if(predicate.test(integer)){
      list2.add(integer);
      }
      }
      return list2;

      }
      }


      复制


      最后修改时间:2020-07-01 13:37:29
      文章转载自227decision,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

      评论