Java - lambda 表达式语法以及练习

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第8天,点击查看活动详情

Lambda 表达式语法

  • Lambda 表达式是用来给【函数式接口】的变量或形参赋值用的
  • 其实本质上, Lambda 表达式是用于实现【函数式接口】的抽象方法

Lambda 表达式语法格式

(形参列表) -> {Lambda体}
复制代码

说明

  • (形参列表)它就是要赋值的函数式接口的抽象方法的(形参列表),照抄
  • { Lambda 体}就是实现这个抽象方法的方法体
  • ->称为 Lambda 操作符(减号和大于号中间不能有空格,而且必须是英文状态下半角输入方式)

优化

Lambda 表达式可以精简

  • { Lambda 体}中只有一句语句时,可以省略{}{;}
  • { Lambda 体}中只有一句语句时,并且这个语句还是一个 return 语句,那么 return 也可以省略,但是如果{;}没有省略的话,return 是不能省略的
  • (形参列表)的类型可以省略
  • (形参列表)的形参个数只有一个,那么可以把数据类型和 ()一起省略,但是形参名不能省略
  • (形参列表)是空参时,()不能省略

示例代码

public class TestLambdaGrammer {
	@Test
	public void test1(){
		//用Lambda表达式给Runnable接口的形参或变量赋值
		/*
		 * 确定两件事,才能写好lambda表达式
		 * (1)这个接口的抽象方法长什么样:
		 * 		public void run()
		 * (2)这个抽象方法的实现要干什么事
		 * 		例如:我要打印“hello lambda"
		 */
		Runnable r = () -> {System.out.println("hello lambda");};
	}
	
	@Test
	public void test2(){
		//lambda体省略了{;}
		Runnable r = () -> System.out.println("hello lambda");
	}
	
	@Test
	public void test3(){
		String[] arr = {"hello","Hello","java","JAVA"};
		
		//为arr数组排序,但是,想要不区分大小写
		/*
		 * public static <T> void sort(T[] a,Comparator<? super T> c)
		 * 这里要用Lambda表达式为Comparator类型的形参赋值
		 * 
		 * 两件事:
		 * (1)这个接口的抽象方法:  int compare(T o1, T o2)
		 * (2)这个抽象方法要做什么事?
		 * 		例如:这里要对String类型的元素,不区分大小写的比较大小
		 */
//		Arrays.sort(arr, (String o1, String o2) -> {return o1.compareToIgnoreCase(o2);});
		
		//省略了{return ;}
//		Arrays.sort(arr, (String o1, String o2) ->  o1.compareToIgnoreCase(o2));
		
		//省略了两个String
		Arrays.sort(arr, (o1, o2) ->  o1.compareToIgnoreCase(o2));
		
		for (String string : arr) {
			System.out.println(string);
		}
	}
	
	@Test
	public void test4(){
		ArrayList<String> list = new ArrayList<>();
		list.add("hello");
		list.add("java");
		list.add("world");
		
		/*
		 * JDK1.8给Collection系列的集合,准确的讲是在Iterable接口中,增加了一个默认方法
		 * 		default void forEach(Consumer<? super T> action) 
		 * 这个方法是用来遍历集合等的。代替原来的foreach循环的。
		 * 
		 * 这个方法的形参是Consumer接口类型,它是函数式接口中消费型接口的代表
		 * 我现在调用这个方法,想要用Lambda表达式为Consumer接口类型形参赋值
		 * 
		 * 两件事:
		 * (1)它的抽象方法:  void  accept(T t)
		 * (2)抽象方法的实现要完成的事是什么
		 * 		例如:这里要打印这个t
		 */
//		list.forEach((String t) -> {System.out.println(t);});
		
		//省略{;}
//		list.forEach((String t) -> System.out.println(t));
		
		//省略String
//		list.forEach((t) -> System.out.println(t));
		
		//可以省略形参()
		list.forEach(t -> System.out.println(t));
	}
}
复制代码

Lambda 表达式练习

练习1:无参无返回值形式

假如有自定义函数式接口 Call

public interface Call {
    void shout();
}
复制代码

在测试类中声明一个如下方法

public static void callSomething(Call call){
		call.shout();
	}
复制代码

在测试类的 main 方法中调用 callSomething 方法,并用 Lambda 表达式为形参 call 赋值

public class TestLambda {
	public static void main(String[] args) {
		callSomething(()->System.out.println("回家吃饭"));
		callSomething(()->System.out.println("我爱你"));
		callSomething(()->System.out.println("滚蛋"));
		callSomething(()->System.out.println("回来"));
	}
	public static void callSomething(Call call){
		call.shout();
	}
}
interface Call {
    void shout();
}
复制代码

练习2:消费型接口

代码示例:Consumer<T>接口

在 JDK1.8 中 Collection 集合接口的父接口 Iterable 接口中增加了一个默认方法:

public default void forEach(Consumer<? super T> action)遍历Collection集合的每个元素,执行“xxx消费型”操作

在 JDK1.8 中 Map 集合接口中增加了一个默认方法:

public default void forEach(BiConsumer<? super K,? super V> action)遍历 Map 集合的每对映射关系,执行“xxx消费型”操作

案例

创建一个 Collection 系列的集合,添加编程语言,调用 forEach 方法遍历查看

创建一个 Map 系列的集合,添加一些 (key,value) 键值对,例如,添加编程语言排名和语言名称,调用 forEach 方法遍历查看

示例代码

	@Test
	public void test1(){
		List<String> list = Arrays.asList("java","c","python","c++","VB","C#");
		list.forEach(s -> System.out.println(s));
    }
	@Test
	public void test2(){
		HashMap<Integer,String> map = new HashMap<>();
		map.put(1, "java");
		map.put(2, "c");
		map.put(3, "python");
		map.put(4, "c++");
        map.put(5, "VB");
        map.put(6, "C#");
		map.forEach((k,v) -> System.out.println(k+"->"+v));
	}
复制代码

练习3:供给型接口

代码示例:Supplier<T>接口

  • 在 JDK1.8 中增加了 StreamAPI,java.util.stream.Stream是一个数据流
  • 这个类型有一个静态方法:public static <T> Stream<T> generate(Supplier<T> s)可以创建 Stream 的对象
  • 包含一个 forEach 方法可以遍历流中的元素:public void forEach(Consumer<? super T> action)

案例

现在调用 Stream 的 generate 方法,来产生一个流对象,并调用 Math.random() 方法来产生数据,为 Supplier 函数式接口的形参赋值,最后调用 forEach 方法遍历流中的数据查看结果

	@Test
	public void test2(){
		Stream.generate(() -> Math.random()).forEach(num -> System.out.println(num));
	}
复制代码

练习4:功能型接口

代码示例:Funtion<T,R>接口

在 JDK1.8 时 Map 接口增加了很多方法,例如:

public default void replaceAll(BiFunction<? super K,? super V,? extends V> function)按照 function 指定的操作替换 map 中的 value

public default void forEach(BiConsumer<? super K,? super V> action)遍历 Map 集合的每对映射关系,执行“xxx消费型”操作

案例

  1. 声明一个Employee员工类型,包含编号、姓名、薪资
  2. 添加n个员工对象到一个HashMap<Integer,Employee>集合中,其中员工编号为 key,员工对象为 value
  3. 调用 Map 的 forEach 遍历集合
  4. 调用 Map 的 replaceAll 方法,将其中薪资低于10000元的,薪资设置为10000
  5. 再次调用 Map的 forEach 遍历集合查看结果

Employee 类

class Employee{
	private int id;
	private String name;
	private double salary;
	public Employee(int id, String name, double salary) {
		super();
		this.id = id;
		this.name = name;
		this.salary = salary;
	}
	public Employee() {
		super();
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getSalary() {
		return salary;
	}
	public void setSalary(double salary) {
		this.salary = salary;
	}
	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", salary=" + salary + "]";
	}
	
}
复制代码

测试类

import java.util.HashMap;

public class TestLambda {
	public static void main(String[] args) {
        Map<Integer, Employee> map = new HashMap<>();
        Employee e1 = new Employee(1, "张三", 8000);
        Employee e2 = new Employee(2, "李四", 9000);
        Employee e3 = new Employee(3, "王五", 10000);
        Employee e4 = new Employee(4, "赵六", 11000);
        Employee e5 = new Employee(5, "钱七", 12000);

        map.put(e1.getId(), e1);
        map.put(e2.getId(), e2);
        map.put(e3.getId(), e3);
        map.put(e4.getId(), e4);
        map.put(e5.getId(), e5);

        // foreach
        map.forEach((id, employee) -> System.out.println(id + "->" + employee));

        // replaceAll
        map.replaceAll((id, employee) -> {
            if (employee.getSalary() < 10000) {
                employee.setSalary(10000);
            }
            return employee;
        });

        // forEach
        map.forEach((id, employee) -> System.out.println(id + "->" + employee));
	}
}
复制代码

练习5:判断型接口

代码示例:Predicate<T>接口

JDK1.8 时,Collecton 接口增加了一下方法,其中一个如下:

public default boolean removeIf(Predicate<? super E> filter) :用于删除集合中满足 filter 指定的条件判断的数据

public default void forEach(Consumer<? super T> action):遍历 Collection 集合的每个元素,执行“xxx消费型”操作

案例

  1. 添加一些字符串到一个Collection集合中
  2. 调用 forEach 遍历集合
  3. 调用 removeIf 方法,删除其中字符串的长度<5的
  4. 再次调用forEach遍历集合
import java.util.ArrayList;

public class TestLambda {
	public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("hello");
        list.add("java");
        list.add("polo");
        list.add("ok");

        // forEach
        list.forEach(System.out::println);

        // removeIf
        list.removeIf(s -> StringUtils.containsIgnoreCase(s, "o"));

        // forEach
        list.forEach(System.out::println);
	}
}
复制代码

练习6:判断型接口

案例

  • 声明一个 Employee 员工类型,包含编号、姓名、性别,年龄,薪资

  • 声明一个 EmployeeSerice 员工管理类,包含一个 ArrayList 集合的属性 all,在 EmployeeSerice 的构造器中,创建一些员工对象,为 all 集合初始化

  • 在 EmployeeSerice 员工管理类中,声明一个方法:ArrayList get(Predicate p),即将满足 p 指定的条件的员工,添加到一个新的 ArrayList 集合中返回

  • 在测试类中创建 EmployeeSerice 员工管理类的对象,并调用 get 方法,分别获取:

    • 所有员工对象
    • 所有年龄超过35的员工
    • 所有薪资高于15000的女员工
    • 所有编号是偶数的员工
    • 名字是“张三”的员工
    • 年龄超过25,薪资低于10000的男员工

Employee类

public class Employee{
	private int id;
	private String name;
	private char gender;
	private int age;
	private double salary;
	
	public Employee(int id, String name, char gender, int age, double salary) {
		super();
		this.id = id;
		this.name = name;
		this.gender = gender;
		this.age = age;
		this.salary = salary;
	}
	public Employee() {
		super();
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getSalary() {
		return salary;
	}
	public void setSalary(double salary) {
		this.salary = salary;
	}
	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", gender=" + gender + ", age=" + age + ", salary=" + salary
				+ "]";
	}
}
复制代码

员工管理类

class EmployeeService{
	private ArrayList<Employee> all;
	public EmployeeService(){
		all = new ArrayList<Employee>();
		all.add(new Employee(1, "张三", '男', 33, 8000));
		all.add(new Employee(2, "翠花", '女', 23, 18000));
		all.add(new Employee(3, "无能", '男', 46, 8000));
		all.add(new Employee(4, "李四", '女', 23, 9000));
		all.add(new Employee(5, "老王", '男', 23, 15000));
		all.add(new Employee(6, "大嘴", '男', 23, 11000));
	}
    public List<Employee> get(Predicate<Employee> p) {
        ArrayList<Employee> result = new ArrayList<>();
        for (Employees emp : all) {
            if (p.test(emp)) {
                result.add(emp);
            }
        }
        System.out.println();
        return result;
    }
}
复制代码

测试类

public class TestLambda {
	public static void main(String[] args) {
		EmployeeService es = new EmployeeService();
		
        EmployeeSerice employeeSerice = new EmployeeSerice();
        employeeSerice.get(emp -> true).forEach(System.out::print);
        employeeSerice.get(emp -> emp.getAge() > 35).forEach(System.out::print);
        employeeSerice.get(emp -> emp.getSalary() > 15000 && emp.getGender() == '女').forEach(System.out::print);
        employeeSerice.get(emp -> emp.getId() % 2 == 0).forEach(System.out::print);
        employeeSerice.get(emp -> StringUtils.equals(emp.getName(), "张三")).forEach(System.out::print);
        employeeSerice.get(emp -> emp.getAge() > 25 && emp.getGender() == '男' && emp.getSalary() < 10000).forEach(System.out::print);
	}
}
复制代码

方法引用与构造器引用

  • Lambda 表达式是可以简化函数式接口的变量与形参赋值的语法
  • 而方法引用和构造器引用是为了简化 Lambda 表达式的
  • 当 Lambda 表达式满足一些特殊的情况时,还可以再简化

特殊情况

Lambda 体只有一句语句,并且是通过调用一个对象/类现有的方法来完成的,如:

  • System.out 对象,调用 println() 方法来完成 Lambda 体
  • Math 类,调用 random() 静态方法来完成 Lambda 体

并且 Lambda 表达式的形参正好是给该方法的实参,如:

  • (t) -> System.out.println(t),都是只有一个参数
  • () -> Math.random() ,都是无参

方法引用

方法引用的语法格式:

实例对象名::实例方法
类名::静态方法
类名::实例方法
复制代码

说明

  • ::称为方法引用操作符(两个:中间不能有空格,而且必须英文状态下半角输入)
  • Lambda 表达式的形参列表,全部在 Lambda 体中使用上了,要么是作为调用方法的对象,要么是作为方法的实参
  • 在整个 Lambda 体中没有额外的数据
	
	@Test
	public void test4(){
        // 不能简化方法引用,因为"hello lambda"这个无法省略
        // Runnable r = () -> System.out.println("hello lambda");
        
        // 打印空行
		Runnable r = System.out::println;
        // 等价写法
        Runnable r1 = () -> System.out.println();
	}
	
	@Test
	public void test3(){
		String[] arr = {"Hello","java","chai"};
        // Arrays.sort(arr, (s1,s2) -> s1.compareToIgnoreCase(s2));
		// 用方法引用简化
		/*
		 * Lambda表达式的形参,第一个(例如:s1)
         * 正好是调用方法的对象,剩下的形参(例如:s2)正好是给这个方法的实参
		 */
		Arrays.sort(arr, String::compareToIgnoreCase);
	}
	
	@Test
	public void test2(){
        // Stream<Double> stream = Stream.generate(() -> Math.random());
		
		// 用方法引用简化
		Stream<Double> stream = Stream.generate(Math::random);
	}
	
	@Test
	public void test1(){
		List<Integer> list = Arrays.asList(1,3,4,8,9);
		
		//list.forEach(t -> System.out.println(t));
		
		//用方法再简化
		list.forEach(System.out::println);
	}
复制代码

构造器引用

  • 当 Lambda 表达式是创建一个对象,并且满足 Lambda 表达式形参,正好是给创建这个对象的构造器的实参列表
  • 当 Lambda 表达式是创建一个数组对象,并且满足 Lambda 表达式形参,正好是给创建这个数组对象的长度

构造器引用的语法格式

  • 类名::new
  • 数组类型名::new

示例代码

public class TestMethodReference {
    @Test
	public void teset04() {
		Stream<Integer> stream = Stream.of(1,2,3);
		Stream<int[]> map = stream.map(int[]::new);
	}
    
	
	//这个方法是模仿HashMap中,把你指定的数组的长度纠正为2的n次方的代码
	//createArray()的作用是,创建一个长度为2的n次方的数组
	public <R> R[] createArray(Function<Integer,R[]> fun,int length){
		int n = length - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        length = n < 0 ? 1 : n + 1;
		return fun.apply(length);
	}
	
	@Test
	public void test3(){
		/*
		 * Function是一个函数式接口,可以用Lambda表达式赋值
		 * Function<T,R>的抽象方法   R apply(T t)
		 * 
		 * createArray这个方法中用的是Function<Integer,R[]> fun。说明T类型已经指定为Integer
		 * 说明
		 */
        // Function<Integer,String[]> f = (Integer len) -> new String[len];
		
		//因为Lambda体是在创建一个数组对象完成的,而且Lambda表达式的形参正好是创建数组用的长度
		//通过构造器引用省略
		Function<Integer,String[]> f = String[]::new;
		String[] array = createArray(f, 10);
		
		System.out.println(array.length);//16
	}
       
    
    @Test
	public void teset02() {
		Stream<String> stream = Stream.of("1.0","2.3","4.4");
		
        // Stream<BigDecimal> stream2 = stream.map(num -> new BigDecimal(num));
		
		Stream<BigDecimal> stream2 = stream.map(BigDecimal::new);
	}
	
	@Test
	public void test1(){
        // Supplier<String> s = () -> new String();//通过供给型接口,提供一个空字符串对象
		
		//构造器引用
		Supplier<String> s = String::new;//通过供给型接口,提供一个空字符串对象
	}

}
复制代码
分类:
后端