lambda表达式
    取代内部类,接口只有一个方法的时候,或者有@FunctionalInterface注解的时候
    @FunctionalInterface是一个标记接口,标志当前接口中只有一个需要实现的函数,修饰的就是函数式接口

    1. // 内部类
    2. Runnable runnable = new Runnable() {
    3. @Override
    4. public void run() {
    5. System.out.println("输出");
    6. }
    7. };
    8. // lambda
    9. Runnable runnable = () -> {
    10. System.out.println("输出");
    11. };
    12. // 如果实现只有一行代码
    13. Runnable runnable = () ->
    14. System.out.println("输出");

    变量的作用域,和匿名函数是一样的,只能引用final类型的外部变量

    Stream流
    使用场景就是处理集合
    使用Stream流程,
    1.创建Stream数据源.stream()
    2.数据处理转换stream
    3.聚合操作.collect()

    1. @Data
    2. public class Student {
    3. private String name;
    4. private Integer age;
    5. private double size;
    6. private double salary;
    7. }
    8. List<Student> studentList = Arrays.asList(
    9. new Student("a43", 18, 188, 35000),
    10. new Student("b53", 30, 188, 45000),
    11. new Student("c66", 26, 188, 55000),
    12. new Student("d110", 24, 188, 36000),
    13. new Student("e34", 32, 188, 43000)
    14. );
    15. @Test
    16. public void test6() {
    17. // 输出["e34","b53","c66","d110"]
    18. List<String> collect = studentList.stream() // 创建一个Stream流对象
    19. .filter(student -> student.getAge() > 20) // 筛选出年龄大于20的学生
    20. .sorted(Comparator.comparingInt(Student::getAge).reversed()) // 排序 reversed为降序
    21. .map(Student::getName)// 映射,最终只需要输出名字,取出name属性
    22. .collect(Collectors.toList());//结果的收集器 创建一个新的list,也可以是set和map
    23. // 数据转为Map
    24. // 输出{"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}}
    25. Map<String, Student> collect1 = studentList.stream()
    26. .collect(Collectors.toMap(Student::getName, Function.identity()));
    27. // 通过年龄分组
    28. // 输出{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}]}
    29. Map<Integer, List<Student>> collect1 = studentList.stream()
    30. .collect(Collectors.groupingBy(Student::getAge));
    31. }
    32. //挨个操作,可以做累加
    33. @Test
    34. public void test6() {
    35. List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
    36. Optional<Integer> reduce = list.stream().reduce((i, j) -> {
    37. i += j;
    38. return i;
    39. });
    40. // 15
    41. System.out.println(reduce.get());
    42. List<String> strings = Arrays.asList("一", "二", "三", "四", "五");
    43. Optional<String> reduce1 = strings.stream().reduce((i, j) -> {
    44. i += j;
    45. return i;
    46. });
    47. // 一二三四五
    48. System.out.println(reduce1.get());
    49. }