Java Lambda表达式

打印 上一主题 下一主题

主题 927|帖子 927|积分 2781

Lambda表达式

Lambda表达式,也可以称为闭包,是Java 8发布的最重要新特性

  • Lambda答应把函数作为一个方法的参数(函数作为参数传递进方法中)
  • 使用Lambda表达式可以使代码变的更加简便紧凑
  • 语法:

    • (parameter) -> expression
    • (parameter) -> { statement; }

  • parameter: 参数列表,如果只有一个参数,可以省略括号,如果没有参数,也需要使用括号;
  • expression 或 { statement; } 是Lambda表达式的主体
我们可以举一个简朴的例子
  1. public class Main {
  2.     public static void main(String[] args) {
  3. //        Lambda表达式计算两数之和
  4.         MathOperation addition = (a, b) -> a + b;
  5.         MathOperation addition2 = (a, b) -> a + b;
  6.         MathOperation addition3 = (a, b) -> a*b;
  7.         System.out.println(addition.operate(5,3));
  8.         System.out.println(addition2.operate(5,3));
  9.         System.out.println(addition3.operate(5,3));
  10.     }
  11. }
  12. interface  MathOperation{
  13.     int operate(int a, int b);
  14. }
复制代码
在上面的例子中,MathOperation 是一个函数式接口,它包含一个抽象方法 operation,Lambda 表达式(a, b) -> a + b 实现了这个抽象方法,表示对两个参数举行相加操纵。
所以,Lambda表达式可以用来实现接口的方法,但是只可以实现一种方法,一种以上如下图
  1. MathOperation operation = (a, b) -> {
  2.             return a / b;
  3.         };
  4. MathOperation operation = (a, b) -> {
  5.             return a * b + 10;
  6.         };
复制代码
重要特征

简便性

Lambda 表达式提供了一种更为简便的语法,尤其实用于函数式接口。相比于传统的匿名内部类,Lambda 表达式使得代码更为紧凑,淘汰了样板代码的编写。
  1. @FunctionalInterface
  2. public interface Runnable {
  3.     /**
  4.      * When an object implementing interface Runnable is used
  5.      * to create a thread, starting the thread causes the object's
  6.      * run method to be called in that separately executing
  7.      * thread.
  8.      * <p>
  9.      * The general contract of the method run is that it may
  10.      * take any action whatsoever.
  11.      *
  12.      * @see     java.lang.Thread#run()
  13.      */
  14.     public abstract void run();
  15. }
复制代码
  1. public class Main {
  2.     public static void main(String[] args) {
  3.         //使用匿名内部类
  4.         Runnable runnable1 = new Runnable() {
  5.             @Override
  6.             public void run() {
  7.                 System.out.println("Hello World!");
  8.             }
  9.         };
  10.         runnable1.run();
  11. // 使用 Lambda 表达式
  12.         Runnable runnable2 = () -> System.out.println("Hello World!");
  13.         runnable2.run();
  14.     }
  15. }
复制代码
函数式编程支持

Lambda 表达式是函数式编程的一种表现,它答应将函数当作参数传递给方法,或者将函数作为返回值,这种支持使得 Java 在函数式编程方面更为灵活,能够更好地处理聚集操纵、并行计算等任务
  1. List<String> names = Arrays.asList("Alice","Bob","Cuiweiyang");
  2. names.forEach(name -> System.out.println(name));
复制代码
实现了一下接口


变量捕获

Lambda 表达式可以访问外部作用域的变量,这种特性称为变量捕获,Lambda 表达式可以隐式地捕获 final 或究竟上是 final 的局部变量。
  1. int  x = 10;
  2. Function function = a -> System.out.println(a+x);//注意返回值类型
  3. function.oper(5);
复制代码
  1. interface Function{
  2.     void oper(int a);
  3. }
复制代码
方法引用

Lambda 表达式可以通过方法引用进一步简化,方法引用答应你直接引用现有类或对象的方法,而不用编写冗余的代码
  1. // 使用方法引用
  2. List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
  3. names.forEach(System.out::println);
复制代码
可并行性

Lambda 表达式能够更方便地实现并行操纵,通过使用 Stream API 结合 Lambda 表达式,可以更容易地实现并行计算,提高程序性能。
  1. // 使用 Lambda 表达式和 Stream API 进行并行计算
  2. List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
  3. int sum =numbers.parallelStream().mapToInt(Integer::intValue).sum();
  4. System.out.println("sum: "+sum);
复制代码
Lambda 表达式的引入使得 Java 编程更加灵活、简便,并推动了函数式编程的发展。
Lambda表达式实例

Lambda 表达式的简朴例子:
  1. // 1. 不需要参数,返回值为 5  
  2. () -> 5  
  3. // 2. 接收一个参数(数字类型),返回其2倍的值  
  4. x -> 2 * x  
  5. // 3. 接受2个参数(数字),并返回他们的差值  
  6. (x, y) -> x – y  
  7. // 4. 接收2个int型整数,返回他们的和  
  8. (int x, int y) -> x + y  
  9. // 5. 接受一个 string 对象,并在控制台打印,不返回任何值(看起来像是返回void)  
  10. (String s) -> System.out.print(s)
复制代码
可以分析一下一下代码
  1. public class Java8Tester {
  2.     public static void main(String []args){
  3.         Java8Tester tester = new Java8Tester();
  4.         // 类型声明
  5.         MathOperation addition = (int a, int b) -> a + b;
  6.         // 不用类型声明
  7.         MathOperation subtraction = (a, b) -> a - b;
  8.         // 大括号中的返回语句
  9.         MathOperation multiplication = (int a, int b) -> { return a * b; };
  10.         // 没有大括号及返回语句
  11.         MathOperation division = (int a, int b) -> a / b;
  12.         System.out.println("10 + 5 = " + tester.operate(10, 5, addition));
  13.         System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction));
  14.         System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication));
  15.         System.out.println("10 / 5 = " + tester.operate(10, 5, division));
  16.         // 不用括号
  17.         GreetingService greetService1 = message ->
  18.                 System.out.println("Hello " + message);
  19.         // 用括号
  20.         GreetingService greetService2 = (message) ->
  21.                 System.out.println("Hello " + message);
  22.         greetService1.sayMessage("Runoob");
  23.         greetService2.sayMessage("Google");
  24.     }
  25.     interface MathOperation {
  26.         int operation(int a, int b);
  27.     }
  28.     interface GreetingService {
  29.         void sayMessage(String message);
  30.     }
  31.     private int operate(int a, int b, MathOperation mathOperation){
  32.         return mathOperation.operation(a, b);
  33.     }
  34. }
复制代码
使用 Lambda 表达式需要注意以下两点:

  • Lambda 表达式主要用来定义行内执行的方法范例接口(比方,一个简朴方法接口)。在上面例子中,我们使用各种范例的 Lambda 表达式来定义 MathOperation 接口的方法,然后我们定义了 operation 的执行。
  • Lambda 表达式免去了使用匿名方法的麻烦,并且给予 Java 简朴但是强大的函数化的编程能力
变量作用域

lambda 表达式只能引用标志了 final 的外层局部变量,这就是说不能在 lambda 内部修改定义在域外的局部变量,否则会编译错误。
  1. public class Java8Tester {
  2.    final static String salutation = "Hello! ";
  3.    
  4.    public static void main(String args[]){
  5.       GreetingService greetService1 = message ->
  6.       System.out.println(salutation + message);
  7.       greetService1.sayMessage("Runoob");
  8.    }
  9.    
  10.    interface GreetingService {
  11.       void sayMessage(String message);
  12.    }
  13. }
复制代码
$ javac Java8Tester.java
$ java Java8Tester
Hello! Runoob
我们也可以直接在 lambda 表达式中访问外层的局部变量:
  1. public class Java8Tester {
  2.     public static void main(String args[]) {
  3.         final int num = 1;
  4.         Converter<Integer, String> s = (param) -> System.out.println(String.valueOf(param + num));
  5.         s.convert(2);  // 输出结果为 3
  6.     }
  7.     public interface Converter<T1, T2> {
  8.         void convert(int i);
  9.     }
  10. }
复制代码
lambda 表达式的局部变量可以不用声明为 final,但是必须不可被后面的代码修改(即隐性的具有 final 的语义)
  1. int num = 1;  
  2. Converter<Integer, String> s = (param) -> System.out.println(String.valueOf(param + num));
  3. s.convert(2);
  4. num = 5;  
  5. //报错信息:Local variable num defined in an enclosing scope must be final or effectively final
复制代码
在 Lambda 表达式当中不答应声明一个与局部变量同名的参数或者局部变量。
  1. String first = "";  
  2. Comparator<String> comparator = (first, second) -> Integer.compare(first.length(), second.length());  //编译会出错
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

鼠扑

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表