JDK 8 Lambda 内置的函数接口

1,799 阅读1分钟

Predicate

  1. Predicate 是新增的函数式接口,位于java.util.function;
  2. Predicate 用于测试传入的数据是否满足判断要求;
  3. Predicate 接口需要实现test()方法进行逻辑判断;

接口定义:

@FunctionalInterface
public interface Predicate<T> {
    boolean test(T t);
}

使用示例:

    public static void PredicateHandlerOne(Predicate<Integer> predicate){
        boolean flag = predicate.test(10);
        System.out.println(flag);
    }
    public static void PredicateHandlerTwo(Integer num){
        Predicate<Integer> predicate = s-> s >= 10;
        boolean flag = predicate.test(num);
        System.out.println(flag);
    }
    public static void PredicateHandlerThred(Integer num,Predicate<Integer> predicate){
        boolean flag = predicate.test(num);
        System.out.println(flag);
    }
    public static void main(String[] args) {
        // n->  (括号里是boolean值)
        PredicateHandlerOne(s -> s>5);
        PredicateHandlerTwo(0);
        PredicateHandlerThred(10,s-> s > 4);
    }

Consumer

Consumer接口:主要的面向的任务是,有一个输入值,没有返回值的情况。

接口定义:

@FunctionalInterface
public interface Consumer<T> {
    void accept(T t);
}

使用示例:

    /**
     * 方法一:  取定长,根据传入的不同的数据
     * @param consumer
     */
    public static void ConsumerHandlerWay(Consumer<String> consumer){
        consumer.accept("xuqiu");
    }

    /**
     * 方法二: 对同一个数据进行处理,根据参数获取不同的长度
     * @param num
     */
    public static void ConsumerHandlerWayTwo(String num){
        Consumer<String> consumer = s ->{
            System.out.println(num);
        };
        consumer.accept(num);
    }

    public static void main(String[] args) {
         // 1. 使用
          ConsumerHandlerWay(s-> System.out.println("输出方法一"+s));
         // 2.
          ConsumerHandlerWayTwo("哈喽,输出方法二");
    }

Function

接受一个输入参数,返回一个结果。
  •         第一个表示输入参数的类型;

    •         第二个表示返回值的类型;

接口定义:

@FunctionalInterface
public interface Function<T, R> {
    R apply(T t);
}

使用示例:

    /**
     * 方法一:  取定长,根据传入的不同的数据
     * @param function
     */
    public static void functionHandlerWay(Function<Integer,String> function){
        String str = function.apply(20);
        System.out.println(str);
    }

    /**
     * 方法二: 对同一个数据进行处理,根据参数获取不同的长度
     * @param num
     */
    public static void funcationHandlerWayTwo(Integer num){
        Function<Integer,String> function = s ->{
            String nums = "1111aaaaa";
            nums = nums.substring(s);
            return nums;
        };
        String resu = function.apply(num);
        System.out.println(resu);
    }

    public static void main(String[] args) {
        //1. 使用
        functionHandlerWay(s -> s +"abcdefg");
        //2. 使用
        funcationHandlerWayTwo(1);
    }