本文共 1793 字,大约阅读时间需要 5 分钟。
在Java中,lambda表达式是用于替代匿名内部类的简洁方式。其基础语法结构为:
(参数列表) -> { 方法体 }; return关键字。// 匿名内部类Runnable runnable = new Runnable() { @Override public void run() { System.out.println("开始执行run方法"); }};// lambda表达式Runnable runnable = () -> { System.out.println("开始执行run方法");};// 最简洁的lambda表达式Runnable runnable = () -> System.out.println("开始执行run方法"); 函数式接口是具有以下特点的接口:
// Consumer接口Consumerconsumer = (aDouble) -> { System.out.println("我的美甲金额" + aDouble);};// Supplier接口Supplier supplier = () -> { return "ssss";};// Function接口Function function = (e) -> { return "今天消费了" + e;};// Predicate接口Predicate predicate = (t) -> { return t > 18;};
// 创建线程并执行lambda表达式Thread thread = new Thread(() -> System.out.println("开始执行run方法"));thread.start(); // 使用lambda表达式排序ListpeopleList = Arrays.sort(peopleList, (a, b) -> a.getAge().compareTo(b.getAge()));
// 调用静态方法int result = Math.sqrt(4);int anotherResult = Math::sqrt(4);
// 调用实例方法String name = user.getName();String anotherName = user::getName;
// 使用BiPredicate引用String的equals方法BiPredicatepredicate = String::equals;boolean equal = predicate.test("zz", "ee");
// 简单构造User user = () -> new User();User user2 = User::new;
// 使用BiFunction构造对象BiFunctionbiFunction = (age, name) -> new User(age, name);User user = biFunction.apply(18, "峥峥");
通过以上内容,我们可以看到lambda表达式在Java编程中的强大能力,尤其是在函数式编程中应用广泛。无论是简化代码逻辑,还是提高代码的可读性,lambda表达式都能发挥重要作用。
转载地址:http://xvmg.baihongyu.com/