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 );}

猜你喜欢

转载自blog.csdn.net/qq_42968048/article/details/84670974