Java函数式接口

发布于 9 天前  13 次阅读


消费型接口:

package com.apesbolg.function;

import java.util.function.Consumer;

public class consumer {
    public static void main(String[] args) {
        Integer[] a = {400};
        //a是数组,是一个引用,所以传递a可以改变里面的值
        Integer[] aa = consumerInterface(a, x -> x[0] = x[0] + 100);
        System.out.println(aa[0]);
    }

    public static Integer[] consumerInterface(Integer[] a, Consumer<Integer[]> c) {
        c.accept(a);
        return a;
    }
}

供给型接口:

package com.apesbolg.function;

import java.util.function.Supplier;

public class supplier {
    public static void main(String[] args) {
        int i = supplierInterface(() -> 500);
        System.out.println(i);
    }

    public static Integer supplierInterface(Supplier<Integer> s) {
        return s.get();
    }
}

函数型接口:

package com.apesbolg.function;

import java.util.function.Function;

public class function {
    public static void main(String[] args) {
        Double b = functionInterface(500, x -> Double.valueOf(x));
        System.out.println(b);
    }

    public static Double functionInterface(Integer a, Function<Integer, Double> f) {
        return f.apply(a);
    }


}

断定型接口:

package com.apesbolg.function;

import java.util.function.Predicate;

public class predicate {
    public static void main(String[] args) {
        Boolean b = predicateInterface(19, x -> x > 18);
        System.out.println(b);
    }

    public static Boolean predicateInterface(Integer a, Predicate<Integer> p) {
        return p.test(a);
    }
}