java8中Lambda表达式写法详解

一、是什么?有什么好处?

Lambda 是一个匿名函数,我们可以把 Lambda 表达式理解为是一段可以传递的代码。可以写出更简洁、更灵活的代码。 注:lambda表达式需要函数式接口(接口中只有一个抽象方法的接口,称为函数式接口。 使用注解 @FunctionalInterface 修饰) 的支持。

二、关于lambda表达式的一些写法

1、无参数,无返回值

//内部类实现方式
Runnable r = new Runnable() {
          
   
  		@Override
  		public void run() {
          
   
  			System.out.println("Hello World!"+Thread.currentThread().getName());
  		}
  	};
//lambda实现方式
Runnable r1 = () -> System.out.println("Hello Lambda!");

2、有一个参数,无返回值

Consumer<String> con = x -> {
          
   
  		System.out.println(x);
  	};
con.accept("我是张刚!");

3、有两个参数,有返回值

Comparator<Integer> com = (x, y) -> {
          
   
  		return Integer.compare(x, y);
  	};
int compare = com.compare(4, 3);
System.out.println(compare);

4、若 Lambda 体中只有一条语句, return 和 大括号都可以省略不写

Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
int compare = com.compare(4, 3);
System.out.println(compare);

三、lambda表达式方法引用

🐖:若 Lambda 体中的功能,已经有方法提供了实现,可以使用方法引用。 1. 对象的引用 :: 实例方法名 2. 类名 :: 静态方法名 3. 类名 :: 实例方法名

1、对象的引用 :: 实例方法名 前提:方法引用所引用的方法(println方法)的参数列表与返回值类型,需要与函数式接口中抽象方法的参数列表和返回值类型保持一致!

PrintStream ps = System.out;
Consumer<String> con = (str) -> ps.println(str);
con.accept("Hello World!");
System.out.println("--------------------------------");
Consumer<String> con2 = ps::println;
con2.accept("Hello Java8!");

2、类名 :: 静态方法名 方法引用所引用的方法(compare方法)的参数列表与返回值类型,需要与函数式接口中抽象方法的参数列表和返回值类型保持一致! 并且所引用的方法(compare方法)必须是静态方法

Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
com.compare(1,2);
System.out.println("-------------------------------------");
Comparator<Integer> com2 = Integer::compare;
com2.compare(1,2);

3、类名 :: 实例方法名 若Lambda 的参数列表的第一个参数,是实例方法的调用者,第二个参数(或无参)是实例方法的参数时

BiPredicate<String, String> bp = (x, y) -> x.equals(y);
System.out.println(bp.test("abc", "abc"));
System.out.println("--------------------------------");
BiPredicate<String, String> bp2 = String::equals;
System.out.println(bp2.test("abc", "abc"));

四、lambda表达式构造器引用

🐖:和方法引用一样,写法如下:

基础类:

@Data //该注解需要引用lombok包
class Employee {
          
   
    private int id;
    private String name;
    private int age;
    private double salary;
   }

1、类名::new 构造器的参数列表,需要与函数式接口中参数列表保持一致!

Function<String, Employee> fun = (str) -> new Employee();
Employee apply1 = fun.apply("a");
System.out.println("--------------");
Function<String, Employee> fun2 = Employee::new;
Employee apply2 = fun2.apply("a");

2、类型[] :: new

Function<Integer, String[]> fun = (args) -> new String[args];
String[] strs = fun.apply(10);
System.out.println(strs.length);
System.out.println("--------------------------");
Function<Integer, Employee[]> fun2 = Employee[]::new;
Employee[] emps = fun2.apply(10);
System.out.println(emps.length);
经验分享 程序员 微信小程序 职场和发展