java8 函数接口

【前言】 java8新特性

 

java8 Optional使用总结

java8 lambda表达式

Java 8 时间日期使用

 

1、函数式接口新特性

java8中引入了函数式接口新特性,使用@FunctionalInterface标识,表示有且只有一个抽象方法,但可以有多个非抽象方法。eg:

package com.notes.java8.functionInterface;

/**
 * 文件描述 函数式接口:
 *      有且仅有一个抽象方法,但是可以有多个非抽象方法的接口。
 **/
@FunctionalInterface
public interface Hello {

    /**
     * abstract 方法,只能有一个
     */
    void hello();

    /**
     * 允许定义默认方法
     */
    default void hi(){
        System.out.println("this is default method");
    }

    /**
     * 允许定义静态方法
     */
    static void hei() {
        System.out.println("this is static method");
    }

    /**
     * 允许定义 java.lang.Object 里的 public 方法
     */
    @Override
    boolean equals(Object obj);
}

2、四大基本函数式接口

> Function<T, R>
接受一个入参T,返回R类型对象,使用apply方法获取方法执行的内容

R apply(T t);

eg:

    User user = new User(88, "bb");

    String name = uft.apply(user);
    System.out.println(name);



    /**
    * Function<T, R> lambda写法
     */
    private static Function<User, String> uft = u -> u.getName();

> Consumer<T>
接受一个参数T,没有返回值,使用accept方法对参数执行操作

void accept(T t);

eg:

        User user = new User(88, "bb");

        uc.accept(user);

        /**
       * Consumer<T> lambda写法
       */
      private static Consumer<User> uc = u -> System.out.println(u.getName());

> Supplier<T>
没有入参,返回T类型结果,使用get方法获取返回结果

T get();

eg:

        User user1 = us.get();
        System.out.println(user1.getName());

        /**
         * Supplier<T> lambda写法
         */
        private static Supplier<User> us = () -> new User(1, "us");

> Predicate<T>
接受一个入参,返回结果为true或者false,使用test方法进行测试并返回测试结果

boolean test(T t);

eg:

        boolean test = up.test(user);
        System.out.println(test);    

        /**
         * Predicate<T>
         */
        private static Predicate<User> up = u -> !u.getName().isEmpty();

其他的函数式接口可参见以下接口示意图

 

posted @ 2019-06-14 14:05  花拾夕  阅读(6217)  评论(0编辑  收藏  举报