函数式编程接口
Java8的库设计师已经帮我们定义了常用的函数式接口。这些接口都在java.util.funtion包下
函数式接口名 | 抽象方法 | 说明 |
---|---|---|
Function<T, R> | R apply(T t); | 接受T返回R |
BiFunction<T, U, R> | R apply(T t, U u); | 接受T,U,返回R |
Supplier | T get(); | 无参返回T |
Consumer < T > | void accept(T t); | 接受T无返回 |
BiConsumer <T, U> | void accept(T t, U u); | 接受T,U无返回 |
Predicate | boolean test(T t) | 接受T,返回boolean |
BiPredicate<T, U> | boolean test(T t, U u); | 接受T,U返回boolean |
- 为了好点记忆,Function有T有R,Supplier无T有R,Consumer有T无R,Predicate有T且B.
- 当然已上列出的函数式接口是较为常见的,如果需要三个参数过着更多参数,我们可以自定义接口来。
- 还有一些非泛型方法如下,Int Long Double 型等
方法引用
-
静态方法的方法引用
-
非静态方法的方法引用
-
构造函数的方法引用
public class NameUseTest {
public static void main(String[] args) {
// 静态方法引用--通过类名调用
Consumer<String> consumerStatic = AloneTest::MyNameStatic;
consumerStatic.accept("alone---static");
//实例方法引用--通过实例调用
AloneTest alone = new AloneTest();
Consumer<String> consumer = alone::myName;
consumer.accept("alone---instance");
// 构造方法方法引用--无参数
Supplier<AloneTest> supplier = AloneTest::new;
System.out.println(supplier.get());
}
}
class AloneTest {
// 静态方法
public static void MyNameStatic(String name) {
System.out.println(name);
}
// 实例方法
public void myName(String name) {
System.out.println(name);
}
// 无参构造方法
public AloneTest() {
}
}