javase1.8以后的新特性
Lambda (参数类型可以省略) (参数名称)->{ 功能代码}
知识点小结 主要用于已经写死的代码 跟业务逻辑毫无关联如:
1.jButton.addActionListener
(
(e)->{System.out.println("LambdaOK");}
);
2.new Thread
(
(Runnable)()->{for(inti=0;i<10;i++){System.out.println(i);}}
).start();
3.函数接口(指的就是只有一个功能的接口)
@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修饰的量或者事实上为final的量(一个变量从头到尾没有变化)
5.介绍函数接口BinaryOperator 接受多个参数的函数接口
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.内部迭代 其实原理是先运行count 再运行filter 并且只运行了一次
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�