javase1.8以后的新特性
Lambda?? (參數(shù)類型可以省略) (參數(shù)名稱)->{ 功能代碼}
知識(shí)點(diǎn)小結(jié)??? 主要用于已經(jīng)寫死的代碼 跟業(yè)務(wù)邏輯毫無(wú)關(guān)聯(lián)如:
1.jButton.addActionListener
(
(e)->{System.out.println("LambdaOK");}
);
2.new Thread????
(
??? (Runnable)()->{for(inti=0;i<10;i++){System.out.println(i);}}
).start();
3.函數(shù)接口(指的就是只有一個(gè)功能的接口)
@FunctionalInterface
interface MyDo
{
??? int doit(int a,int b);
}
public class LambdaEx01
{
??? public static int dodo(MyDodoi,int a,int b)
??? {
?????? return doi.doit(a,b);???
??? }
??? public static void main(Stringargs[])
??? {
?????? int result=0;
??????
?????? MyDo add=(a,b)->{returna+b;};
?????? result=dodo(add,12,5);
?????? System.out.println(result);
??????
?????? MyDo aa=(a,b)->{returna*b;};
?????? result=dodo(aa,12,5);
?????? System.out.println(result);
??? }
}
4.Lambda中只能用final修飾的量或者事實(shí)上為final的量(一個(gè)變量從頭到尾沒有變化)
5.介紹函數(shù)接口BinaryOperator? 接受多個(gè)參數(shù)的函數(shù)接口
import java.util.function.BinaryOperator;
public class LambdaEx5
{
??? public static intcal(BinaryOperator bo,int a,int b)
??? {
?????? return bo.apply(a, b);
??? }??
??? public static void main(Stringargs[])
??? {????????????
?????? BinaryOperatorbo=(x,y)->x*y;
?????? BinaryOperatorbo2=(x,y)->x%y;
??????
?????? System.out.println(cal(bo,12,3));
?????? System.out.println(cal(bo2,12,5));
??? }
}
6.內(nèi)部迭代?其實(shí)原理是先運(yùn)行count 再運(yùn)行filter? 并且只運(yùn)行了一次
import java.util.*;
public class LambdaEx01
{
??? public static void main(Stringargs[])
??? {
?????? Liststudents=new ArrayList<>();
?????? students.add(newStudent("97001","張三",18));
?????? students.add(newStudent("97002","李四",19));
?????? students.add(new Student("97003","王五",21));
??????
?????? long count =students.stream()
????????????? .filter(Student->Student.id.equals("97001"))
????????????? .count();
?????? System.out.println(count);
?????? long count2=students.stream()
????????????? .filter(Student->Student.age.equals(21))
????????????? .count();
?????? System.out.println(count2);
??? }
}
?p?