1、Lambda表达式简单说就是一个方法
2、它可以作为参数在方法见传递
3、但只能在使用了FunctionalInterface的地方
4、FunctionalInterface是单个方法的接口,且使用了@FunctionalInterface的注解
5、Lambda的好处是语法简洁,同时在多核CPU下运行效率高
6、Lambda表达式的语法
基本语法:
(parameters) -> expression或
(parameters) ->{ statements; }
实例:
一:runnable接口符合Lambda的要求(3和4点就是使用Lambda表达式的基本要求)
public class LearnLambda1 {
public static void main(String [] args){
for(int i = 0; i<1000; i++)
new Thread(()->
System.out.println("I am thread "+Thread.currentThread().getId())).start();
}
}
二、List.forEach(Consumer c)中的Consumer接口也是只有一个方法,并且使用了@FunctionalInterface的注解
public class LearnLambda2 {
public static void main(String [] args){
List<Person> persons = new ArrayList<Person>();
persons.add(new Person("张三","化学",60));
persons.add(new Person("李四","生物",78));
persons.add(new Person("王五","物理",69));
persons.add(new Person("钱六","计算机",83));
persons.add(new Person("赵七","英语",90));
persons.forEach((Person p)->System.out.println(p.name));
System.out.println();
persons.forEach((Person p)->System.out.println(p.name + ":" + p.department));
System.out.println();
persons.forEach((Person p)->System.out.println(p.name + ":" + p.score));
}
}
public class Person {
public String name;
public String department;
public int score;
public Person(String name, String department, int score) {
this.name = name;
this.department = department;
this.score = score;
}
}
三、Predicate接口也是也是只有一个方法,并且使用了@FunctionalInterface的注解(接口详细信息请看API)
public class LearnLambda3 {
public static void main(String [] args){
List<Person> persons = new ArrayList<Person>();
persons.add(new Person("张三","化学",60));
persons.add(new Person("李四","生物",78));
persons.add(new Person("王五","物理",69));
persons.add(new Person("钱六","计算机",83));
persons.add(new Person("赵七","化学",90));
// filterPrint(persons,(Person p)->p.department.equals("化学"));
filterPrint(persons,(Person p)->p.score>70);
}
public static void filterPrint(List<Person> persons,Predicate<Person> predicate){
for(Person p : persons){
if(predicate.test(p))
System.out.println(p.name);
}
}
}
四、当然我们可以自定义接口来使用lambda
@FunctionalInterface
interface Studey{
void studing();
}
public class LearnLambda4 {
public static void doSomething(Studey study){//可以有多个参数,方法内容也可以自定义
study.studing();
}
public static void main(String [] args){
doSomething(()->System.out.println("我正在学习lambda"));
}
}