Java: Ekspresi Lambda - apa itu?
Menerapkan antarmuka dengan hanya satu metode abstrak biasanya relatif membingungkan. Ekspresi Lambda menawarkan obat. Bagaimana Anda bisa menggunakannya.
Java: Ekspresi Lambda
Sebagai contoh, pertimbangkan antarmuka fungsional berikut: » uji antarmuka {void test method (String x); } «.
- Alih-alih menerapkan metode abstrak dengan cara klasik, Anda juga dapat menghemat waktu dan menggunakan ekspresi lambda.
- Untuk melakukan ini, pertama mengimplementasikan antarmuka, kemudian masukkan parameter metode abstrak dan akhirnya pernyataan sebenarnya dari metode: » Test test = (String x) -> System.out.println (x); ". Operator » -> « baru diperkenalkan untuk ini.
- Jika metode ini tidak memiliki parameter, biarkan kurung kosong. Beberapa parameter dipisahkan seperti biasa dengan koma.
- Jika fungsi harus menjalankan beberapa perintah, batasi isi fungsi Lamda dengan kurung keriting: » Tes uji = (String x) -> {if (x.length ()> 0) {System.out.println (x) ; } else {System.out.println ("no character"); }}; ".
- Ekspresi Lambda sangat praktis untuk iterasi menggunakan ArrayLists. Jika " daftar " adalah ArrayList, Anda dapat, misalnya, menggunakan " liste.forEach ((x) -> System.out.println (x)); «Keluarkan semua elemen daftar.
- Anda juga dapat menggunakan Ekspresi Lambda untuk menetapkan nilai balik metode abstrak. Mari kita pertimbangkan antarmuka » antarmuka menghitung {int compute (int a, int b); } «. Dengan perintah » tambahkan aritmatika = (int a, int b) -> a + b; Misalnya, metode untuk menjumlahkan dua angka diimplementasikan.