lambda表达式
取代内部类,接口只有一个方法的时候,或者有@FunctionalInterface注解的时候
@FunctionalInterface是一个标记接口,标志当前接口中只有一个需要实现的函数,修饰的就是函数式接口
// 内部类
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("输出");
}
};
// lambda
Runnable runnable = () -> {
System.out.println("输出");
};
// 如果实现只有一行代码
Runnable runnable = () ->
System.out.println("输出");
变量的作用域,和匿名函数是一样的,只能引用final类型的外部变量
Stream流
使用场景就是处理集合
使用Stream流程,
1.创建Stream数据源.stream()
2.数据处理转换stream
3.聚合操作.collect()
@Data
public class Student {
private String name;
private Integer age;
private double size;
private double salary;
}
List<Student> studentList = Arrays.asList(
new Student("a43", 18, 188, 35000),
new Student("b53", 30, 188, 45000),
new Student("c66", 26, 188, 55000),
new Student("d110", 24, 188, 36000),
new Student("e34", 32, 188, 43000)
);
@Test
public void test6() {
// 输出["e34","b53","c66","d110"]
List<String> collect = studentList.stream() // 创建一个Stream流对象
.filter(student -> student.getAge() > 20) // 筛选出年龄大于20的学生
.sorted(Comparator.comparingInt(Student::getAge).reversed()) // 排序 reversed为降序
.map(Student::getName)// 映射,最终只需要输出名字,取出name属性
.collect(Collectors.toList());//结果的收集器 创建一个新的list,也可以是set和map
// 数据转为Map
// 输出{"b53":{"age":30,"name":"b53","salary":45000,"size":188},"a43":{"age":18,"name":"a43","salary":35000,"size":188},"d110":{"age":24,"name":"d110","salary":36000,"size":188},"c66":{"age":26,"name":"c66","salary":55000,"size":188},"e34":{"age":32,"name":"e34","salary":43000,"size":188}}
Map<String, Student> collect1 = studentList.stream()
.collect(Collectors.toMap(Student::getName, Function.identity()));
// 通过年龄分组
// 输出{32:[{"age":32,"name":"e34","salary":43000,"size":188}],18:[{"age":18,"name":"a43","salary":35000,"size":188}],24:[{"age":24,"name":"d110","salary":36000,"size":188}],26:[{"age":26,"name":"c66","salary":55000,"size":188}],30:[{"age":30,"name":"b53","salary":45000,"size":188}]}
Map<Integer, List<Student>> collect1 = studentList.stream()
.collect(Collectors.groupingBy(Student::getAge));
}
//挨个操作,可以做累加
@Test
public void test6() {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
Optional<Integer> reduce = list.stream().reduce((i, j) -> {
i += j;
return i;
});
// 15
System.out.println(reduce.get());
List<String> strings = Arrays.asList("一", "二", "三", "四", "五");
Optional<String> reduce1 = strings.stream().reduce((i, j) -> {
i += j;
return i;
});
// 一二三四五
System.out.println(reduce1.get());
}