Java 8 Lambda表达示例

在这篇文章中,将演示各种示例,以了解Lambda表达式的强大功能。 Lambda表达式是在Java SE 8中引入的,因此我们需要安装java 8或更高版本来编译和运行以下示例。

示例#1

在这个例子中,我们将执行加法,减法,乘法和除法等算术运算。

文件:LambdaExample1.java

package com.yiibai.tutorial.lambda;  /**  * @author yiibai  */  /**  * Functional Interface  */ interface Arithmetic {     int operation(int a, int b); }  public class LambdaExample1 {     public static void main(String[] args) {          // Addition using Lambda expression         Arithmetic addition = (int a, int b) -> (a + b);         // Arithmetic addition = (int a, int b) -> {return a + b;};          System.out.println("Addition = " + addition.operation(5, 6));          // Subtraction using Lambda expression         Arithmetic subtraction = (int a, int b) -> (a - b);         // Arithmetic addition = (int a, int b) -> {return a - b;};          System.out.println("Subtraction = " + subtraction.operation(5, 3));          // Multiplication using Lambda expression         Arithmetic multiplication = (int a, int b) -> (a * b);         // Arithmetic addition = (int a, int b) -> {return a * b;};          System.out.println("Multiplication = " + multiplication.operation(4, 6));          // Division using Lambda expression         Arithmetic division = (int a, int b) -> (a / b);         // Arithmetic addition = (int a, int b) -> {return a * b;};          System.out.println("Division = " + division.operation(12, 6));      } } 

执行上面示例代码,得到以下结果:

Addition = 11 Subtraction = 2 Multiplication = 24 Division = 2 

示例#2

一个简单的Java Lambda程序,用于检查给定的数字是偶数还是奇数。

文件:LambdaExample2 .java

package com.yiibai.tutorial.lambda;  /**  * @author yiibai  */  /**  * Functional Interface  */ interface EvenOdd {     void check(int a); }  public class LambdaExample2 {     public static void main(String[] args) {         // Lambda Expression         EvenOdd evenOdd = (int a) -> {             if(a%2==0){                 System.out.println("Number "+a+" is even.");             }else{                 System.out.println("Number "+a+" is odd.");             }         };          //Check numbers         evenOdd.check(5);         evenOdd.check(8);     } } 

执行上面示例代码,得到以下结果:

Number 5 is odd. Number 8 is even. 

示例#3

用于计算圆的面积的Java Lambda程序。

文件:LambdaExample3.java

package com.yiibai.tutorial.lambda;  /**  * @author yiibai  */  /**  * Functional Interface  */ interface Circle {     double area(double r); }  public class LambdaExample3 {     public static void main(String[] args) {         // Lambda Expression         Circle circle=(double r)-> (Math.PI*r*r);          //Print area of circle         System.out.println("Area of Circle = "+circle.area(5));     } } 

执行上面示例代码,得到以下结果:

Area of Circle = 78.53981633974483 

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/264091.html

(0)
上一篇 2022年6月7日
下一篇 2022年6月7日

相关推荐

发表回复

登录后才能评论