1. 程式人生 > >Java筆記丨21 Lambda表示式

Java筆記丨21 Lambda表示式

Lambda(λ expression)表示式

Java8中開始引入

是介面或者說是介面函式的簡寫

基本寫法

(引數)->結果

引數是()或1個或多個引數

結果是指表示式或語句或{語句}

如:(String s)->s.length()

x->x*x;

()->{System.out.println(“aaa”);}

大體上相當於其他語言的“匿名函式”或“函式指標

在Java8中它實際上是“匿名類的一個例項

示例:積分LambdaIntegral.java

double d = Integral( new Fun(){

                     public double fun(double x){

                            return Math.sin(x);

                     }

}, 0, Math.PI, 1e-5 );

 

d = Integral( x->Math.sin(x),0, Math.PI, 1e-5 );

 

完整程式碼:

@FunctionalInterface

interface Fun { double fun( double x );}



public class LambdaIntegral

{

       public static void main(String[] args)

       {

              double d = Integral( new Fun(){

                     public double fun(double x){

                            return Math.sin(x);

                     }

              }, 0, Math.PI, 1e-5 );



              d = Integral( x->Math.sin(x),

                     0, Math.PI, 1e-5 );

              System.out.println( d );



              d = Integral( x->x*x, 0, 1, 1e-5 );

              System.out.println( d );



       }



       static double Integral(Fun f, double a, double b, double eps)// 積分計算

       {

              int n,k;

              double fa,fb,h,t1,p,s,x,t=0;



              fa=f.fun(a);

              fb=f.fun(b);



              n=1;

              h=b-a;

              t1=h*(fa+fb)/2.0;

              p=Double.MAX_VALUE;



              while (p>=eps)

              {

                     s=0.0;

                     for (k=0;k<=n-1;k++)

                     {

                            x=a+(k+0.5)*h;

                            s=s+f.fun(x);

                     }



                     t=(t1+h*s)/2.0;

                     p=Math.abs(t1-t);

                     t1=t;

                     n=n+n;

                     h=h/2.0;

              }

              return t;

       }



}

示例:LambdaRunnable.java

class LambdaRunnable  {

    public static void main(String argv[]) {

              Runnable doIt =  new Runnable(){

                     public void run(){

                            System.out.println("aaa");

                     }

              };

              new Thread( doIt ).start();



              Runnable doIt2 = ()->System.out.println("bbb");

              new Thread( doIt2 ).start();



              new Thread( ()->System.out.println("ccc") ).start();

             

    }

}

Lambda大大簡化了書寫

執行緒的例子中:new Thread(()->{…}).start();

積分的例子中:

    d = Integral( x->Math.sin(x),0, 1, EPS );

    d = Integral( x->x*x,0, 1, EPS );

    d = Integral( x->1,0, 1, EPS );

按鈕事件處理中:btn.addActionListener(e->{…});

更重要的是,它將程式碼也當成資料來處理

 

能寫成Lambda的介面的條件

由於Lambda只能表示一個函式,所以能寫成Lambda的介面要求包含且最多隻能有一個抽象函式。這樣的介面可以(但不強求)用註記

@FunctionalInterface來表示。稱為函式式介面

如:

@FunctionalInterface

interface Fun { double fun( double x );}