Java8的Lambda表达式
Lambda表达式与函数式接口
函数式接口是只包含一个抽象方法声明的接口。java.lang.Runnable 就是一种函数式接口,在 Runnable 接口中只声明了一个方法 void run()。我们使用匿名内部类来实例化函数式接口的对象,有了 Lambda 表达式,这一方式可以得到简化。
@FunctionalInterface 是 Java 8 新加入的一种接口,用于指明该接口类型声明是根据 Java 语言规范定义的函数式接口。
如下所示,在WorkerInterface接口上,使用FunctionalInterface声明后,在这个接口里面不写方法或者写两个方法,编译器都会报错。
@FunctionalInterface
public interface WorkerInterface{
public void doSomeWork();
}
Lambda表达式的使用
1). Thread Runable
new Thread(()-> System.out.println(Thread.currentThread().getName())).start();
new Thread(()-> {
System.out.println(Thread.currentThread().getName());
}).start();
2). 有参数无返回值
@FunctionalInterface
public interface Interface1{
public void work1(String str);
}
// 带类型
Interface1 interface1=(String str)->{
System.out.println("Interface1带类型的:"+str);
};
interface1.work1("传入参数");
// 不带类型
Interface1 interface11=(str)->{
System.out.println("Interface1不带类型的:"+str);
};
interface11.work1("传入参数");
// 不带括号
Interface1 interface12=str->
System.out.println("Interface1不带括号的:"+str);
interface12.work1("传入参数");
// 不带大括号
Interface1 interface13=str->{
System.out.println("Interface1不带大括号:"+str);
};
interface13.work1("传入参数");
3). 有参数有返回值
Interface2 interface21=clz->"直接返回:"+clz.getName();
System.out.println(interface21.work2(String.class));
Interface2 interface22=clz->{
return "return返回:"+clz.getName();
};
System.out.println(interface22.work2(Integer.class));
java8的双冒号表达式,Iterable接口的forEach遍历,Consumer接口(函数式接口)
List<String> list = Arrays.asList("aaa","bbb","ccc");
System.out.println("通常的遍历方式");
// 1.通常的遍历方式
for(String str: list) {
System.out.println(str);
}
System.out.println("使用Lambda表达式遍历");
// 2.使用Lambda表达式遍历
list.forEach(str -> {
System.out.println(str);
});
System.out.println("使用::遍历");
// 3.使用::遍历
list.forEach(System.out::println);
// 下面的方法和上面等价,使用的是函数式编程
Consumer<String> methodParam = System.out::println; //方法参数
list.forEach(x -> methodParam.accept(x));//方法执行accept