一、引言

java8最大的特性就是引入Lambda表达式,即函数式编程,可以将行为进行传递。总结就是:使用不可变值与函数,函数对不可变值进行处理,映射成另一个值。

二、Java重要的函数式接口

1、什么是函数式接口

函数接口是只有一个抽象方法的接口,用作 Lambda 表达式的类型。使用@FunctionalInterface注解修饰的类,编译器会检测该类是否只有一个抽象方法或接口,否则,会报错。可以有多个默认方法,静态方法。

1.1 java8自带的常用函数式接口。

函数接口 抽象方法 功能 参数 返回类型 实例
Predicate test(T t) 判断真假 T boolean 9龙的身高大于185cm吗?
Consumer accept(T t) 消费消息 T void 输出一个值
Function R apply(T t) 将T映射为R(转换功能) T R 获得student对象的名字
Supplier T get() 生产消息 None T 工厂方法
UnaryOperator T apply(T t) 一元操作 T T 逻辑非 !
BinaryOperator apply(T t,U u) 二元操作 (T,T) T 求两个数的乘积 *
  1. public class Test {
  2. public static void main(String[] args) {
  3. Predicatepredicate = x -> x > 185;
  4. Student student = new Student("9龙", 23, 175);
  5. System.out.println(
  6. "9龙的身高高于185吗?:" + predicate.test(student.getStature()));
  7. Consumer<String> consumer = System.out::println;
  8. consumer.accept("命运由我不由天");
  9. Function<student, </student, String> function = Student::getName;
  10. String name = function.apply(student);
  11. System.out.println(name);
  12. Suppliersupplier =
  13. () -> Integer.valueOf(BigDecimal.TEN.toString());
  14. System.out.println(supplier.get());
  15. UnaryOperator<Boolean> unaryOperator = uglily -> !uglily;
  16. Boolean apply2 = unaryOperator.apply(true);
  17. System.out.println(apply2);
  18. BinaryOperatoroperator = (x, y) -> x * y;
  19. Integer integer = operator.apply(2, 3);
  20. System.out.println(integer);
  21. test(() -> "我是一个演示的函数式接口");
  22. }
  23. /**
  24. * 演示自定义函数式接口使用
  25. *
  26. * @param worker
  27. */
  28. public static void test(Worker worker) {
  29. String work = worker.work();
  30. System.out.println(work);
  31. }
  32. public interface Worker {
  33. String work();
  34. }
  35. }
  36. //9龙的身高高于185吗?:false
  37. //命运由我不由天
  38. //9龙
  39. //10
  40. //false
  41. //6
  42. //我是一个演示的函数式接口

以上演示了lambda接口的使用及自定义一个函数式接口并使用。下面,我们看看java8将函数式接口封装到流中如何高效的帮助我们处理集合。
注意:Student::getName例子中这种编写lambda表达式的方式称为方法引用。格式为ClassNmae::methodName。是不是很神奇,java8就是这么迷人。
“
示例:本篇所有示例都基于以下三个类。OutstandingClass:班级;Student:学生;SpecialityEnum:特长。
感受 lambda 之美! - 图1

1.2 惰性求值与及早求值

惰性求值:只描述Stream,操作的结果也是Stream,这样的操作称为惰性求值。惰性求值可以像建造者模式一样链式使用,最后再使用及早求值得到最终结果。
及早求值:得到最终的结果而不是Stream,这样的操作称为及早求值。

2、常用的流

2.1 collect(Collectors.toList())

  1. 将流转换为list。还有toSet(),toMap()等。及早求值。
  2. public class TestCase {
  3. public static void main(String[] args) {
  4. ListstudentList = Stream.of(new Student("路飞", 22, 175),
  5. new Student("红发", 40, 180),
  6. new Student("白胡子", 50, 185)).collect(Collectors.toList());
  7. System.out.println(studentList);
  8. }
  9. }
  10. //输出结果
  11. //[Student{name='路飞', age=22, stature=175, specialities=null},
  12. //Student{name='红发', age=40, stature=180, specialities=null},
  13. //Student{name='白胡子', age=50, stature=185, specialities=null}]

下面用一个案例演示toList、toSet和toMap:

  1. public class StreamTest {
  2. public static void main(String[] args) {
  3. List<Integer> list = Arrays.asList(1, 6, 3, 4, 6, 7, 9, 6, 20);
  4. List<Integer> listNew = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toList());
  5. Set<Integer> set = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toSet());
  6. List<Person> personList = new ArrayList<Person>();
  7. personList.add(new Person("Tom", 8900, 23, "male", "New York"));
  8. personList.add(new Person("Jack", 7000, 25, "male", "Washington"));
  9. personList.add(new Person("Lily", 7800, 21, "female", "Washington"));
  10. personList.add(new Person("Anni", 8200, 24, "female", "New York"));
  11. Map<?, Person> map = personList.stream().filter(p -> p.getSalary() > 8000)
  12. .collect(Collectors.toMap(Person::getName, p -> p));
  13. System.out.println("toList:" + listNew);
  14. System.out.println("toSet:" + set);
  15. System.out.println("toMap:" + map);
  16. }
  17. }

2.1.1统计(count/averaging)

Collectors提供了一系列用于数据统计的静态方法:

  • 计数:count
  • 平均值:averagingInt、averagingLong、averagingDouble
  • 最值:maxBy、minBy
  • 求和:summingInt、summingLong、summingDouble
  • 统计以上所有:summarizingInt、summarizingLong、summarizingDouble

案例:统计员工人数、平均工资、工资总额、最高工资。

  1. public class StreamTest {
  2. public static void main(String[] args) {
  3. List<Person> personList = new ArrayList<Person>();
  4. personList.add(new Person("Tom", 8900, 23, "male", "New York"));
  5. personList.add(new Person("Jack", 7000, 25, "male", "Washington"));
  6. personList.add(new Person("Lily", 7800, 21, "female", "Washington"));
  7. // 求总数
  8. Long count = personList.stream().collect(Collectors.counting());
  9. // 求平均工资
  10. Double average = personList.stream().collect(Collectors.averagingDouble(Person::getSalary));
  11. // 求最高工资
  12. Optional<Integer> max = personList.stream().map(Person::getSalary).collect(Collectors.maxBy(Integer::compare));
  13. // 求工资之和
  14. Integer sum = personList.stream().collect(Collectors.summingInt(Person::getSalary));
  15. // 一次性统计所有信息
  16. DoubleSummaryStatistics collect = personList.stream().collect(Collectors.summarizingDouble(Person::getSalary));
  17. System.out.println("员工总数:" + count);
  18. System.out.println("员工平均工资:" + average);
  19. System.out.println("员工工资总和:" + sum);
  20. System.out.println("员工工资所有统计:" + collect);
  21. }
  22. }

2.1.2分组(partitioningBy/groupingBy)

  • 分区:将stream按条件分为两个Map,比如员工按薪资是否高于8000分为两部分。
  • 分组:将集合分为多个Map,比如员工按性别分组。有单级分组和多级分组。

微信图片_20220513105933.png
案例:将员工按薪资是否高于8000分为两部分;将员工按性别和地区分组

  1. public class StreamTest {
  2. public static void main(String[] args) {
  3. List<Person> personList = new ArrayList<Person>();
  4. personList.add(new Person("Tom", 8900, "male", "New York"));
  5. personList.add(new Person("Jack", 7000, "male", "Washington"));
  6. personList.add(new Person("Lily", 7800, "female", "Washington"));
  7. personList.add(new Person("Anni", 8200, "female", "New York"));
  8. personList.add(new Person("Owen", 9500, "male", "New York"));
  9. personList.add(new Person("Alisa", 7900, "female", "New York"));
  10. // 将员工按薪资是否高于8000分组
  11. Map<Boolean, List<Person>> part = personList.stream().collect(Collectors.partitioningBy(x -> x.getSalary() > 8000));
  12. // 将员工按性别分组
  13. Map<String, List<Person>> group = personList.stream().collect(Collectors.groupingBy(Person::getSex));
  14. // 将员工先按性别分组,再按地区分组
  15. Map<String, Map<String, List<Person>>> group2 = personList.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea)));
  16. System.out.println("员工按薪资是否大于8000分组情况:" + part);
  17. System.out.println("员工按性别分组情况:" + group);
  18. System.out.println("员工按性别、地区:" + group2);
  19. }
  20. }

2.1.3接合(joining)

joining可以将stream中的元素用特定的连接符(没有的话,则直接连接)连接成一个字符串。

  1. public class StreamTest {
  2. public static void main(String[] args) {
  3. List<Person> personList = new ArrayList<Person>();
  4. personList.add(new Person("Tom", 8900, 23, "male", "New York"));
  5. personList.add(new Person("Jack", 7000, 25, "male", "Washington"));
  6. personList.add(new Person("Lily", 7800, 21, "female", "Washington"));
  7. String names = personList.stream().map(p -> p.getName()).collect(Collectors.joining(","));
  8. System.out.println("所有员工的姓名:" + names);
  9. List<String> list = Arrays.asList("A", "B", "C");
  10. String string = list.stream().collect(Collectors.joining("-"));
  11. System.out.println("拼接后的字符串:" + string);
  12. }
  13. }

2.2 filter

顾名思义,起过滤筛选的作用。内部就是Predicate接口。惰性求值。
感受 lambda 之美! - 图3
比如我们筛选出出身高小于180的同学。

  1. public class TestCase {
  2. public static void main(String[] args) {
  3. Liststudents = new ArrayList<>(3);
  4. students.add(new Student("路飞", 22, 175));
  5. students.add(new Student("红发", 40, 180));
  6. students.add(new Student("白胡子", 50, 185));
  7. Listlist = students.stream()
  8. .filter(stu -> stu.getStature() < 180)
  9. .collect(Collectors.toList());
  10. System.out.println(list);
  11. }
  12. }
  13. //输出结果
  14. //[Student{name='路飞', age=22, stature=175, specialities=null}]

2.3 map

转换功能,内部就是Function接口。惰性求值
感受 lambda 之美! - 图4

  1. public class TestCase {
  2. public static void main(String[] args) {
  3. Liststudents = new ArrayList<>(3);
  4. students.add(new Student("路飞", 22, 175));
  5. students.add(new Student("红发", 40, 180));
  6. students.add(new Student("白胡子", 50, 185));
  7. Listnames = students.stream().map(student -> student.getName())
  8. .collect(Collectors.toList());
  9. System.out.println(names);
  10. }
  11. }
  12. //输出结果
  13. //[路飞, 红发, 白胡子]

例子中将student对象转换为String对象,获取student的名字。

2.4 flatMap

将多个Stream合并为一个Stream。惰性求值
感受 lambda 之美! - 图5

  1. public class TestCase {
  2. public static void main(String[] args) {
  3. Liststudents = new ArrayList<>(3);
  4. students.add(new Student("路飞", 22, 175));
  5. students.add(new Student("红发", 40, 180));
  6. students.add(new Student("白胡子", 50, 185));
  7. ListstudentList = Stream.of(students,
  8. asList(new Student("艾斯", 25, 183),
  9. new Student("雷利", 48, 176)))
  10. .flatMap(students1 -> students1.stream()).collect(Collectors.toList());
  11. System.out.println(studentList);
  12. }
  13. }
  14. //输出结果
  15. //[Student{name='路飞', age=22, stature=175, specialities=null},
  16. //Student{name='红发', age=40, stature=180, specialities=null},
  17. //Student{name='白胡子', age=50, stature=185, specialities=null},
  18. //Student{name='艾斯', age=25, stature=183, specialities=null},
  19. //Student{name='雷利', age=48, stature=176, specialities=null}]

调用Stream.of的静态方法将两个list转换为Stream,再通过flatMap将两个流合并为一个。

2.5 max和min

我们经常会在集合中求最大或最小值,使用流就很方便。及早求值。

  1. public class TestCase {
  2. public static void main(String[] args) {
  3. Liststudents = new ArrayList<>(3);
  4. students.add(new Student("路飞", 22, 175));
  5. students.add(new Student("红发", 40, 180));
  6. students.add(new Student("白胡子", 50, 185));
  7. Optionalmax = students.stream()
  8. .max(Comparator.comparing(stu -> stu.getAge()));
  9. Optionalmin = students.stream()
  10. .min(Comparator.comparing(stu -> stu.getAge()));
  11. //判断是否有值
  12. if (max.isPresent()) {
  13. System.out.println(max.get());
  14. }
  15. if (min.isPresent()) {
  16. System.out.println(min.get());
  17. }
  18. }
  19. }
  20. //输出结果
  21. //Student{name='白胡子', age=50, stature=185, specialities=null}
  22. //Student{name='路飞', age=22, stature=175, specialities=null}

max、min接收一个Comparator(例子中使用java8自带的静态函数,只需要传进需要比较值即可。)并且返回一个Optional对象,该对象是java8新增的类,专门为了防止null引发的空指针异常。
可以使用max.isPresent()判断是否有值;可以使用max.orElse(new Student()),当值为null时就使用给定值;也可以使用max.orElseGet(() -> new Student());这需要传入一个Supplier的lambda表达式。

2.6 count

统计功能,一般都是结合filter使用,因为先筛选出我们需要的再统计即可。及早求值

  1. public class TestCase {
  2. public static void main(String[] args) {
  3. Liststudents = new ArrayList<>(3);
  4. students.add(new Student("路飞", 22, 175));
  5. students.add(new Student("红发", 40, 180));
  6. students.add(new Student("白胡子", 50, 185));
  7. long count = students.stream().filter(s1 -> s1.getAge() < 45).count();
  8. System.out.println("年龄小于45岁的人数是:" + count);
  9. }
  10. }
  11. //输出结果
  12. //年龄小于45岁的人数是:2

2.7 reduce

reduce 操作可以实现从一组值中生成一个值。在上述例子中用到的 count 、 min 和 max 方法,因为常用而被纳入标准库中。事实上,这些方法都是 reduce 操作。及早求值。
感受 lambda 之美! - 图6

  1. //求和操作
  2. public class TestCase {
  3. public static void main(String[] args) {
  4. List<Integer> list = Arrays.asList(1, 3, 2, 8, 11, 4);
  5. // 求和方式1
  6. Optional<Integer> sum = list.stream().reduce((x, y) -> x + y);
  7. // 求和方式2
  8. Optional<Integer> sum2 = list.stream().reduce(Integer::sum);
  9. // 求和方式3
  10. Integer sum3 = list.stream().reduce(0, Integer::sum);
  11. //方式4
  12. Integer reduce = Stream.of(1, 2, 3, 4).reduce(0, (acc, x) -> acc+ x);
  13. System.out.println(reduce);
  14. }
  15. }
  16. //输出结果
  17. //10
  18. //求乘积
  19. Optional<Integer> product = list.stream().reduce((x, y) -> x * y);
  20. // 求最大值方式1
  21. Optional<Integer> max = list.stream().reduce((x, y) -> x > y ? x : y);
  22. // 求最大值写法2
  23. Integer max2 = list.stream().reduce(1, Integer::max);

案例二:求所有员工的工资之和和最高工资。

  1. public class StreamTest {
  2. public static void main(String[] args) {
  3. List<Person> personList = new ArrayList<Person>();
  4. personList.add(new Person("Tom", 8900, 23, "male", "New York"));
  5. personList.add(new Person("Jack", 7000, 25, "male", "Washington"));
  6. personList.add(new Person("Lily", 7800, 21, "female", "Washington"));
  7. personList.add(new Person("Anni", 8200, 24, "female", "New York"));
  8. personList.add(new Person("Owen", 9500, 25, "male", "New York"));
  9. personList.add(new Person("Alisa", 7900, 26, "female", "New York"));
  10. // 求工资之和方式1:
  11. Optional<Integer> sumSalary = personList.stream().map(Person::getSalary).reduce(Integer::sum);
  12. // 求工资之和方式2:
  13. Integer sumSalary2 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(),
  14. (sum1, sum2) -> sum1 + sum2);
  15. // 求工资之和方式3:
  16. Integer sumSalary3 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(), Integer::sum);
  17. // 求最高工资方式1:
  18. Integer maxSalary = personList.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(),
  19. Integer::max);
  20. // 求最高工资方式2:
  21. Integer maxSalary2 = personList.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(),
  22. (max1, max2) -> max1 > max2 ? max1 : max2);
  23. System.out.println("工资之和:" + sumSalary.get() + "," + sumSalary2 + "," + sumSalary3);
  24. System.out.println("最高工资:" + maxSalary + "," + maxSalary2);
  25. }
  26. }

我们看得reduce接收了一个初始值为0的累加器,依次取出值与累加器相加,最后累加器的值就是最终的结果。

三、高级集合类及收集器

3.1 转换成值

收集器,一种通用的、从流生成复杂值的结构。只要将它传给 collect 方法,所有的流就都可以使用它了。标准类库已经提供了一些有用的收集器,以下示例代码中的收集器都是从 java.util.stream.Collectors 类中静态导入的。

  1. public class CollectorsTest {
  2. public static void main(String[] args) {
  3. Liststudents1 = new ArrayList<>(3);
  4. students1.add(new Student("路飞", 23, 175));
  5. students1.add(new Student("红发", 40, 180));
  6. students1.add(new Student("白胡子", 50, 185));
  7. OutstandingClass ostClass1 = new OutstandingClass("一班", students1);
  8. //复制students1,并移除一个学生
  9. Liststudents2 = new ArrayList<>(students1);
  10. students2.remove(1);
  11. OutstandingClass ostClass2 = new OutstandingClass("二班", students2);
  12. //将ostClass1、ostClass2转换为Stream
  13. StreamclassStream = Stream.of(ostClass1, ostClass2);
  14. OutstandingClass outstandingClass = biggestGroup(classStream);
  15. System.out.println("人数最多的班级是:" + outstandingClass.getName());
  16. System.out.println("一班平均年龄是:" + averageNumberOfStudent(students1));
  17. }
  18. /**
  19. * 获取人数最多的班级
  20. */
  21. private static OutstandingClass biggestGroup(StreamoutstandingClasses) {
  22. return outstandingClasses.collect(
  23. maxBy(comparing(ostClass -> ostClass.getStudents().size())))
  24. .orElseGet(OutstandingClass::new);
  25. }
  26. /**
  27. * 计算平均年龄
  28. */
  29. private static double averageNumberOfStudent(Liststudents) {
  30. return students.stream().collect(averagingInt(Student::getAge));
  31. }
  32. }
  33. //输出结果
  34. //人数最多的班级是:一班
  35. //一班平均年龄是:37.666666666666664

maxBy或者minBy就是求最大值与最小值。

3.2 转换成块

常用的流操作是将其分解成两个集合,Collectors.partitioningBy帮我们实现了,接收一个Predicate函数式接口。
感受 lambda 之美! - 图7
将示例学生分为会唱歌与不会唱歌的两个集合。

  1. public class PartitioningByTest {
  2. public static void main(String[] args) {
  3. //省略Liststudents的初始化
  4. Map> listMap = students.stream().collect(
  5. Collectors.partitioningBy(student -> student.getSpecialities().
  6. contains(SpecialityEnum.SING)));
  7. }
  8. }

3.3 数据分组

数据分组是一种更自然的分割数据操作,与将数据分成 ture 和 false 两部分不同,可以使用任意值对数据分组。Collectors.groupingBy接收一个Function做转换。
感受 lambda 之美! - 图8
如图,我们使用groupingBy将根据进行分组为圆形一组,三角形一组,正方形一组。
例子:根据学生第一个特长进行分组

  1. public class GroupingByTest {
  2. public static void main(String[] args) {
  3. //省略Liststudents的初始化
  4. Map> listMap =
  5. students.stream().collect(
  6. Collectors.groupingBy(student -> student.getSpecialities().get(0)));
  7. }
  8. }

Collectors.groupingBy与SQL 中的 group by 操作是一样的。

3.4 字符串拼接

如果将所有学生的名字拼接起来,怎么做呢?通常只能创建一个StringBuilder,循环拼接。使用Stream,使用Collectors.joining()简单容易。

  1. public class JoiningTest {
  2. public static void main(String[] args) {
  3. Liststudents = new ArrayList<>(3);
  4. students.add(new Student("路飞", 22, 175));
  5. students.add(new Student("红发", 40, 180));
  6. students.add(new Student("白胡子", 50, 185));
  7. String names = students.stream()
  8. .map(Student::getName).collect(Collectors.joining(",","[","]"));
  9. System.out.println(names);
  10. }
  11. }
  12. //输出结果
  13. //[路飞,红发,白胡子]

joining接收三个参数,第一个是分界符,第二个是前缀符,第三个是结束符。也可以不传入参数Collectors.joining(),这样就是直接拼接。

四、总结

本篇主要从实际使用讲述了常用的方法及流,使用java8可以很清晰表达你要做什么,代码也很简洁。本篇例子主要是为了讲解较为简单,大家可以去使用java8重构自己现有的代码,自行领会lambda的奥妙。
本文说的Stream要组合使用才会发挥更大的功能,链式调用很迷人,根据自己的业务去做吧。