JUC-四个函数式接口&lambda

187 阅读1分钟

定义

  • 有且只有一个方法抽象方法的接口,可以有其他的方法.
  • 在定义"函数式接口"时,为防止发生定义错误.可以使用 @FunctionalInterface 注解,强制按照"函数式接口"的语法检查,如果语法错误.编译器将会方法错误. 格式:
@FunctionalInterface
interface Myfunction<T>{
     void apply(T t);
}

四大函数式接口

Fuction

函数型接口

//对类型为T的参数进行一些操作后返回R
@FunctionalInterface
public interface Function<T, R> {
    R apply(T t);
}

Predicate

断定型接口

// 对传入的参数T进行一些操作,返回一个boolean值
@FunctionalInterface
public interface Predicate<T> {
    boolean test(T t);
}

Supplier

供给型接口

// 返回一个类型T的对象
@FunctionalInterface
public interface Supplier<T> {

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

消费型接口

// 对参数T进行操作,无返回
@FunctionalInterface
public interface Consumer<T> {

    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);
    }

使用

public class FunctionTest {
    public static void main(String[] args) {
        //按我们正常的方法定义一个匿名内部类来使用
        Myfunction<String> test = new Myfunction<String>() {
            @Override
            public void apply(String o) {
                System.out.println(o);
            }
        };
        // 通过Lambda表达式来使用
        Myfunction test=(str)->{System.out.printf(str.toString());};
       test.apply("test");
       // Predicate的使用
       Predicate<String> p=(str)->{return str.isEmpty();};
       System.out.println(p.test(""));
       System.out.println(p.test("test"));
       
    }
}

Lambda表达式

Java8新特性

语法:

(parameters) -> expression
或
(parameters) ->{ statements; }

例子

void a(String a);====(a)->{System.out.print(a);}
void a(); ==== ()->{}
String b(); === ()->{return "hello";}
String b(String c); === (str)->{retrun "hello"+str;}
String b(String c);===(String str)->{retrun "hello"+str;}

( ) 内放参数,{ } 内放操作

虽然Lambda表达式是函数,但在Java中它是对象,因为它依附于特定的对象类型——函数式接口。因为它实现了对应函数式接口中的一个抽象方法,也可以说它实现了整个接口,Lambda表达式就是接口的实现类