//老的写法
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Hello World");
}
}).run();
//新的写法
new Thread(
() -> System.out.println("lambda:hello world")
).run();
1. -> 替代了 类名、方法名 前提:函数接口
/**
* 函数式接口是指内部只有一个抽象方法的接口
*/
public interface MyInterface {
int add(int a ,int b);
}
//老的写法
MyInterface myInterface1 = new MyInterface() {
@Override
public int add(int a, int b) {
return a + b;
}
};
//新的写法,括号里面是参数
MyInterface myInterface2 = (a, b) -> a+b;
2. 在集合中的应用
// 在 ArrayList的应用
List<Integer> idList = new ArrayList<>(Arrays.asList(1,2,3,4,5,6));
idList.forEach(new Consumer<Integer>() {
@Override
public void accept(Integer i) {
System.out.println(i);
}
});
idList.forEach((i)-> System.out.println("lambda:"+i));
//Map 中的应用
Map<String,String> map = new HashMap<>();
map.put("a","1");
map.put("b","2");
map.put("c","3");
map.forEach((k,v)-> System.out.println("lambda: k:"+k + " v:"+v));
3.stream()
@Data
public class Student {
private String name;
private String sex;
public Student(String name,String sex){
this.name = name;
this.sex = sex;
}
@Override
public String toString() {
return name + " : " + sex;
}
}
// 得到stream:Collection.stream()、Arrays.stream(T[] array)
// 1.中间操作 distinct() filter() map() 等
// 2.结束操作 collect() forEach() 等
Student student1 = new Student("zhao","male");
Student student2 = new Student("qian","male");
Student student3 = new Student("sun","male");
Student student4 = new Student("li","female");
List<Student> list = new ArrayList<>(Arrays.asList(student1,student2,student3,student4));
// 比如 获取 学生的姓名 的list Student::getName 方法的等同于student -> {return student.getName(); })
List<String> nameList = list.stream().map(Student::getName).collect(Collectors.toList());
System.out.println(nameList);
// 比如 生成一个 学生姓名 + student的 map Function.identity() 代表对象本身
Map<String,Student> map = list.stream().collect(Collectors.toMap(Student::getName, Function.identity()));
System.out.println(map);
// groupBy 按性别归类学生
Map<String,List<Student>> sexAndStudentMap = list.stream().collect(Collectors.groupingBy(Student::getSex));
System.out.println(sexAndStudentMap);
Map<String,List<String>> sexAndNameMap = list.stream().collect(Collectors.groupingBy(Student::getSex,
Collectors.mapping(Student::getName,Collectors.toList())));
System.out.println(sexAndNameMap);
以上是常用的一些场景,关于具体的一些操作,可查看原代码上的注释,一般都会有示例,例如:
image.png
参考资料:https://github.com/CarpenterLee/JavaLambdaInternals
网友评论