1、概念
函数式编程,是一个匿名函数,即没有函数名的函数,简化调用匿名函数的过程
优点:简化我们匿名内部类的调用,代码变得更加精简
2、函数接口定义
1. 在接口中只能有一个抽象方法
2. @FunctionalInterface 标记为该接口为函数接口
3. 可以通过default 修饰为普通方法
4. 可以定义object类中的方法
@FunctionalInterface
public interface MyFunctionalInterface {
void add();
default void get() {
}
String toString();
}
3、基础语法
() 参数列表
-> 分隔
{} 方法体
(a,b)->{
}
4、代码案例
public interface AcanthopanaxInterface {
void get();
}
AcanthopanaxInterface acanthopanaxInterface = () -> {
System.out.println("使用lamdba表达式调用方法");
};
AcanthopanaxInterface acanthopanaxInterface2 = () ->
System.out.println("mayikt");
acanthopanaxInterface.get();
@FunctionalInterface
public interface YouShenInterface {
String get(int i, int j);
}
YouShenInterface youShenInterface = (i, j) -> {
System.out.println("mayikt:" + i + "," + j);
return i + "-" + j;
};
YouShenInterface youShenInterface2 = (i, j) -> i + "-" + j;
System.out.println(youShenInterface.get(1, 1));
ArrayList<String> strings = new ArrayList<>();
strings.add("mayikt");
strings.add("xiaowei");
strings.add("xiaomin");
// strings.forEach(new Consumer() {
// @Override
// public void accept(Object o) {
// System.out.println("o:" + o);
// }
// });
strings.forEach((o) -> {
System.out.println(o);
});
5、方法引用基本使用
1. 方法引用使用一对冒号::
2. 主要有三种语法格式:
对象::实例方法名
类::静态方法名
类::实例方法名
Consumer<String> consumer1 = System.out::println;
consumer1.accept("hehe");
BiPredicate<String, String> bp1 = (x, y) -> x.equals(y);
BiPredicate<String, String> bp2 = String::equals;
Supplier<Passenger> supplier1 = () -> new Passenger();
Supplier<Passenger> supplier2 = Passenger::new;
BiFunction<String, String, Passenger> function1 = (x, y) -> new Passenger(x, y);
BiFunction<String, String, Passenger> function2 = Passenger::new;
Function<Integer, String[]> fun1 = (x) -> new String[x];
String[] strs1 = fun1.apply(10);
Function<Integer, String[]> fun2 = String[]::new;
String[] strs2 = fun2.apply(10);