lambda表達(dá)式的定義
Lambda:
In programming languages such as Lisp, Python and Ruby lambda is an operator used to denote anonymous
functions or closures, following the usage of lambda calculus
在編程語言Lisp, Python 和Ruby中,lambda是一種操作符,用于指定匿名函數(shù)或者閉包,遵循 λ-calculus
在Python、JavaScript等函數(shù)式編程語言之中,Lambda表達(dá)式的類型就是函數(shù)。而在Java中,Lambda表達(dá)式的類型是對象,必須依附于函數(shù)式接口(Functional Interface)。
java中的lambda表達(dá)式是一種匿名函數(shù);沒有名字、方法返回值類型以及訪問修飾符;
為何需要lambda表達(dá)式
- Java中無法將函數(shù)作為參數(shù)傳遞,一個方法的返回值也不能是一個函數(shù)。
- 寫起來簡單、優(yōu)雅,對新人很
友好。 - 編程范式的互相影響以及
借鑒。
基本語法
()-> { }
- 完整的語法是(type1 arg1,type2 arg2)->{body}
- 小括號內(nèi)是方法的參數(shù),花括號內(nèi)是方法的實(shí)現(xiàn),當(dāng)參數(shù)只有一個,實(shí)現(xiàn)只有一行時,小括號和花括號都可以省略。
基本使用示例
- 監(jiān)聽Jbutton的點(diǎn)擊事件
public class JavaSwing {
public static void main(String[] args) {
JFrame jframe = new JFrame("A Frame");
JButton jButton = new JButton("A Button");
//匿名函數(shù)寫法
jButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Pressed");
}
});
// λ寫法
jButton.addActionListener( e -> System.out.println("Pressed"));
jframe.add(jButton);
jframe.pack();
jframe.setVisible(true);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
其中 e -> System.out.println("Pressed")
e代表event,JVM的類型推斷認(rèn)為此處事件一定是一個ActionEvent類型,故可以省略聲明 ActionEvent e,從而直接使用變量 e
list.forEach( i -> System.out.println(i));中的 i 也用到了類型推斷。
2.遍歷一個List
List<Integer> list = Arrays.asList(0,1, 2, 3, 4, 5, 6, 7, 8,9);
//list.forEach(Integer i -> System.out.println(i));
list.forEach(i -> System.out.println(i));//JVM根據(jù)上文List<Integer>推斷出此處 i 的類型為Integer
3.創(chuàng)建一個線程
new Thread(() -> System.out.println("hello")).start();