首页 > 代码库 > Lamda表达式使用

Lamda表达式使用

 1 public class Lambda {
 2 
 3     public static void main(String[] args) {
 4 
 5         Lambda lambda=new Lambda();
 6         String something="oop print somthing";
 7         String something1="oop print something2";
 8         String something2="lambda print something";
 9 
10         lambda.printSomething(something);
11         
12         Printer printer=new Printer(){
13             @Override
14             public void print(String something){
15                 System.out.println(something);
16             }
17         };
18         //use lammbda expression
       //lambda表达式的使用形式是(arg1,arg2,...)->{ 代码块}
        //和上面利用构造函数构造接口实现对象的作用是一样的。但是看起来更加简洁。
19 Printer printer1= something3->System.out.println(something3); 20 21 22 lambda.printSomething(something1, printer); 23 lambda.printSomething(something2, printer1); 24 25 } 26 /* 27 * 28 */ 29 public void printSomething(String something){ 30 System.out.println(something); 31 32 } 33 public void printSomething(String something,Printer printer) { 34 printer.print(something); 35 36 } 37 } 38 39 /* 40 * function interface
  *这里申明一个函数式接口:只有一个函数的接口
  *Lambda 表达式引入的目标是:Lambda表达式原被定义为一个函数式接口的内联实现。
41 */ 42 interface Printer{ 43 public void print(String something); 44 45 }

  lambda能够写出更加紧凑的代码,便于阅读和跟踪。在性能和多核处理方法上也具有不少好处,详细需要了解stream API.

public class Lambda {
public static void main(String[] args) {
Lambda lambda=new Lambda();String something="oop print somthing";String something1="oop print something2";String something2="lambda print something";
lambda.printSomething(something);Printer printer=new Printer(){@Overridepublic void print(String something){System.out.println(something);}};//use lammbda expressionPrinter printer1= something3->System.out.println(something3);
lambda.printSomething(something1, printer);lambda.printSomething(something2, printer1);}/* *  */public void printSomething(String something){System.out.println(something);}public void printSomething(String something,Printer printer) {printer.print(something);}}
/* * function interface */interface Printer{public void print(String something);}

Lamda表达式使用