java8系列-02 函数式接口(Function、Consumer、Predicate、Supplier)

image

上一章已经说了函数式接口的基本概念(java8系列-01 Lambdas 表达式)。函数式接口(Functional Interface)说白了就是只包含了一个抽象方法的接口。下面来剖析一下最常用的四类函数式接口:

提示:本章更多的用代码来叙述,不会更多的文字。

Function功能型函数式接口

上一章有讲到,Function接口是接收一个T类型的参数,返回一个R类型的结果。

Function接口源码

@FunctionalInterface
public interface Function<T, R> {

    // 输入一个T类型的参数,然后对此参数进行操作后返回一个R类型的结果
    R apply(T t);

    // 先执行before函数的apply方法,再执行当前函数的apply方法的函数对象
    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }

    // 先执行当前函数的apply方法,再执行after函数的apply方法的函数对象
    default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }

    // 再执行apply之后,返回输入参数的函数对象
    static <T> Function<T, T> identity() {
        return t -> t;
    }
}

代码例子

public class FunctionTest {
    static String modifyU(String str, Function<String,String> funs){
        return funs.apply(str);
    }

    static String modifyU2(String str, Function<String,String> funs){
        return funs.andThen(funs).apply(str);
    }

    static String modifyU3(String str, Function<String,String> funs){
        return funs.compose(funs).compose(funs).apply(str);
    }

    public static void main(String[] args) {
        User u = new User();
        // lambdas表达式
        String header = modifyU("hello ", (x)->x.concat(u.getName()==null?"Stranger":u.getName()));
        System.out.println(header); // 输出hello Stranger

        // 匿名内部类的形式
        String header2 = modifyU("hello ", new Function<String, String>() {
            @Override
            public String apply(String s) {
                return s.concat(u.getName()==null?"Stranger":u.getName());
            }
        });
        System.out.println(header2); // 输出hello Stranger

        // addThen方法使用
        String header3 = modifyU2("hello ",(x)->x.concat(u.getName()==null?"Stranger ":u.getName()));
        System.out.println(header3); // 输出hello Stranger Stranger

        // compose方法使用
        String header4 = modifyU3("hello ",(x)->x.concat(u.getName()==null?"Stranger ":u.getName()));
        System.out.println(header4); // 输出hello Stranger Stranger Stranger
    }
}

Consumer消费型函数式接口

Consumer接口接收一个T类型的参数,不返回结果

接口源码

@FunctionalInterface
public interface Consumer<T> {

    // 对于给定的参数执行操作
    void accept(T t);

     // 先执行当前函数的accept方法,再执行after函数的accept方法的函数对象
    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }
}

代码例子

public class ConsumerTest {
    static void modifyU4(String str, Consumer<String> cons){
        cons.accept(str);
    }

    public static void main(String[] args) {
        // lambdas表达式
        modifyU4("Hello ",(x)-> System.out.println(x+"java8")); //输出Hello java8
        // 内部类的形式
        modifyU4("Hello ", new Consumer<String>() {
            @Override
            public void accept(String s) {
                System.out.println(s+"java8"); //输出Hello java8
            }
        });
    }
}

Predicate断言型函数式接口

Predicate接收一个T类型的参数,返回一个boolen类型的结果

接口源码

@FunctionalInterface
public interface Predicate<T> {

    // 根据指定的参数来计算其boolean值
    boolean test(T t);

    // 传入一个Predicate函数,返回一个此参数的boolen和另一个Predicate函数的boolean的逻辑与运算
    default Predicate<T> and(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }

    // 返回此函数的非运算
    default Predicate<T> negate() {
        return (t) -> !test(t);
    }

    // 返回此函数与另一个函数的或运算
    default Predicate<T> or(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) || other.test(t);
    }

    /**
     * Returns a predicate that tests if two arguments are equal according
     * to {@link Objects#equals(Object, Object)}.
     */
    static <T> Predicate<T> isEqual(Object targetRef) {
        return (null == targetRef)
                ? Objects::isNull
                : object -> targetRef.equals(object);
    }
}

代码例子

public class PredicateTest {

    static boolean modifyU5(User u, Predicate<User> pre){
       return pre.test(u);
    }

    static Predicate<User> modifyU6(User u, Predicate<User> pre){
        return pre.negate();
    }

    public static void main(String[] args) {
        User user = new User();
        System.out.println(modifyU5(user, (e)-> user.getName() != null)); // 打印false

        System.out.println(modifyU5(user,modifyU6(user,(e)-> user.getName() != null))); // true
        
        // 更多请自行尝试
    }
}

Supplier供给型函数式接口

不接受参数,返回一个T类型的结果

接口源码

@FunctionalInterface
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}

代码例子

public class SupplierTest {

    static String modifyU7(Supplier<String> supplier){
        return supplier.get();
    }

    public static void main(String[] args) {
        // lamdas表达式
        String str = "HelloJava8";
        System.out.println(modifyU7(()-> String.valueOf(str.length()))); // 输出10
    }
}


觉得还行可以点个星星哦

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容