3-1 JDK8 Lambda表达式
什么是 Lambda 表达式?
在JDK8之前,Java是不支持函数式编程的,所谓的函数编程,即可理解是将一个函数(也称为“行为”)作为一个参数进行传递,面向对象编程是对数据的抽象(各种各样的POJO类),而函数式编程则是对行为的抽象(将行为作为一个参数进行传递)
与传统方式的对比
1)、新建线程
传统方式:
public class Main {
public static void main(String[] args) {
new Thread(new Runnable(){
@Override
public void run() {
System.out.println("啦啦啦啦");
}
}).start();
}
}
使用Lambda表达式:
public class Main {
public static void main(String[] args) {
new Thread(()-> System.out.println("啦啦啦啦")).start();
}
}
2)、集合容器字符串排序
传统方式:
public class Main {
public static void main(String[] args) {
List<String> list = Arrays.asList("aaa","ggg","ffff","ccc");
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String a, String b) {
return b.compareTo(a);
}
}
);
for (String string : list) {
System.out.println(string);
}
}
}
Lambda 表达式方式:
public class Main {
public static void main(String[] args) {
List<String> list = Arrays.asList("aaa","ggg","ffff","ccc");
Collections.sort(list, (a,b) -> a.compareTo(b));
for (String string : list) {
System.out.println(string);
}
}
}
使用方法详解
使用条件:
当一个方法所需的参数为一个接口时,并且这个接口只有一个方法时。具备Lambda 表达式的使用条件。
格式解析:
当这个方法没有参数时。
public class Main {
public static void main(String[] args) {
/*
* 方式一(方法体为单条语句)
* () -> 执行的单条语句
*/
new Thread(()-> System.out.println("线程1")).start();
/*
* 方式一(方法体为多条语句)
* () -> {
* 执行语句1;
* ···
* 执行语句n;
* }
*/
new Thread(()-> {
System.out.println("线程2");
}).start();
}
}
当这个方法有参数时
public class Main {
public static void main(String[] args) {
/*
* 方法一个参数
* 方法体为单条语句示例,方法体多条语句略
* 主要是参数格式变化,方法体无变化
*/
Interface interface1 = a -> System.out.println(a); //只有参数是一个的时候可以省略括号()
Interface interface2 = (a) -> System.out.println(a);
Interface interface3 = (int a) -> System.out.println(a);
/*
* 方法多个参数
* 方法体为单条语句示例,方法体多条语句略
* 主要是参数格式变化,方法体无变化
*/
Interface interface4 = (a,b) -> System.out.println(a);
Interface interface5 = (int a,int b) -> System.out.println(a);
}
}
未经授权不得转载或转载请注明出处