java8新特性-lambda表达式&方法引用&streamApi
Lambda表达式
本质:lambda表达式是函数式接口的实例
格式: -> :lambda操作符 或 箭头操作符 ->左边:lambda形参列表 (其实就是接口中的抽象方法的形参列表) ->右边:lambda体 (其实就是重写的抽象方法的方法体) 总结: ->左边:lambda形参列表的参数类型可以省略(类型推断);如果lambda形参列表只有一个参数,其一对()也可以省略 ->右边:lambda体应该使用一对{}包裹;如果lambda体只有一条执行语句(可能是return语句),省略这一对{}和return关键字
演变过程
@Test public void test(){ // 匿名函数 Comparator<Integer> com1 = new Comparator<Integer>() { public int compare(Integer o1, Integer o2) { return Integer.compare(o1, o2); } }; // lambda:本质是接口的实例,lambda体重写了接口的抽象方法 // 因为函数式接口已经确定了调用的方法,因此省略后只有方法体(可推导性) Comparator<Integer> com2 = (a,b) -> Integer.compare(a,b); // 方法引用 Comparator<Integer> com3 = Integer::compare; int c = com3.compare(1, 2); System.out.println(c); }
函数式接口
java.util.function包下定义了丰富的函数式接口
定义:
如果一个接口中,只声明了一个抽象方法,则此接口就称为函数式接口。我们可以在一个接口上使用 @FunctionalInterface 注解,这样做可以检查它是否是一个函数式接口。
java内置四大核心函数式接口:
| 函数式接口 | 参数类型 | 返回值类型 | 抽象方法 |
|
|
T | void | void accept(T t); |
|
|
- | T | T get(); |
|
Function<T, R> 函数型接口 |
T | R | R apply(T t); |
|
|
T | boolean | boolean test(T t); |
// 消费型接口,参数类型T,返回类型void @FunctionalInterface public interface Consumer<T> { void accept(T t); } // 供给型接口,无参数,返回类型T @FunctionalInterface public interface Supplier<T> { T get(); } // 函数型接口,参数类型T,返回类型R @FunctionalInterface public interface Function<T, R> { R apply(T t); } // 断定型接口,参数类型T,返回类型Boolean @FunctionalInterface public interface Predicate<T> { boolean test(T t); }
方法引用 & 构造器引用
方法引用:本质上就是Lambda表达式,所以方法引用,也是函数式接口的实例。
方法引用使用要求:要求接口中的抽象方法的形参列表和返回值类型与方法引用的方法的形参列表和返回值类型相同(仅针对以下情况1和2)
- 对象 :: 非静态方法
- 类 :: 静态方法
- 类 :: 非静态方法 (java语法中是不允许的,但此处可以)
使用举例:
Employee类:
1 // 使用lombok 2 @data 3 public class Employee { 4 5 private int id; 6 private String name; 7 private int age; 8 private double salary 9 10 }
EmployeeData类:
1 public class EmployeeData { 2 3 public static List<Employee> getEmployees(){ 4 List<Employee> list = new ArrayList<>(); 5 6 list.add(new Employee(1001, "马化腾", 34, 6000.38)); 7 list.add(new Employee(1002, "马云", 12, 9876.12)); 8 list.add(new Employee(1003, "刘强东", 33, 3000.82)); 9 list.add(new Employee(1004, "雷军", 26, 7657.37)); 10 list.add(new Employee(1005, "李彦宏", 65, 5555.32)); 11 list.add(new Employee(1006, "比尔盖茨", 42, 9500.43)); 12 list.add(new Employee(1007, "任正非", 26, 4333.32)); 13 list.add(new Employee(1008, "扎克伯格", 35, 2500.32)); 14 15 return list; 16 } 17 18 }
方法引用代码示例:
public class MethodRefTest { /** * 情况一:对象 :: 实例方法 */ //Supplier中的T get() //Employee中的String getName() @Test public void test1() { Employee emp = new Employee(1001,"Tom",23,5600); // 匿名内部类 Supplier<String> sup1 = new Supplier<String>() { @Override public String get() { return emp.getName(); } }; // lambda Supplier<String> sup2 = () -> emp.getName(); // 方法引用 Supplier<String> sup3 = emp::getName; System.out.println(sup3.get()); } /** * 情况二:类 :: 静态方法 */ //Comparator中的int compare(T t1,T t2) //Integer中的int compare(T t1,T t2) @Test public void test2() { // 匿名内部类 Comparator<Integer> com1 = new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return Integer.compare(o1,o2); } }; // lambda Comparator<Integer> com2 = (t1,t2) -> Integer.compare(t1,t2); // 方法引用 Comparator<Integer> com3 = Integer::compare; System.out.println(com3.compare(12,12)); } /** * 情况三:类 :: 实例方法 (比较特殊) * 如下:参数1作为调用者,参数2作为方法参数 */ // Comparator中的int comapre(T t1,T t2) // String中的int t1.compareTo(t2) @Test public void test3() { // 匿名内部类 Comparator<String> com1 = new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareTo(o2); } }; // lambda Comparator<String> com2 = (s1,s2) -> s1.compareTo(s2); // 方法引用 Comparator<String> com3 = String :: compareTo; System.out.println(com3.compare("abd","abm")); } // Function中的R apply(T t) 如下:t就是employee // Employee中的String t.getName(); @Test public void test4() { Employee employee = new Employee(1001, "Jerry", 23, 6000); // 匿名内部类 Function<Employee,String> func1 = new Function<Employee, String>() { @Override public String apply(Employee employee) { return employee.getName(); } }; // lambda Function<Employee,String> func2 = e -> e.getName(); // 方法引用 Function<Employee,String> func3 = Employee::getName; System.out.println(func3.apply(employee)); } }
构造器引用代码示例:
1 /** 2 * 一、构造器引用 3 * 和方法引用类似,函数式接口的抽象方法的形参列表和构造器的形参列表一致。 4 * 抽象方法的返回值类型即为构造器所属的类的类型 5 * 6 * 二、数组引用 7 * 大家可以把数组看做是一个特殊的类,则写法与构造器引用一致。 8 */ 9 public class ConstructorRefTest { 10 /** 11 * 构造器引用 12 */ 13 //Supplier中的T get() 14 //Employee的空参构造器:Employee() 15 @Test 16 public void test1(){ 17 18 Supplier<Employee> sup = new Supplier<Employee>() { 19 @Override 20 public Employee get() { 21 return new Employee(); 22 } 23 }; 24 25 26 Supplier<Employee> sup1 = () -> new Employee(); 27 System.out.println(sup1.get()); 28 29 30 Supplier<Employee> sup2 = Employee :: new; 31 System.out.println(sup2.get()); 32 } 33 34 //Function中的R apply(T t) 35 @Test 36 public void test2(){ 37 Function<Integer,Employee> func1 = id -> new Employee(id); 38 Employee employee = func1.apply(1001); 39 System.out.println(employee); 40 41 42 Function<Integer,Employee> func2 = Employee :: new; 43 Employee employee1 = func2.apply(1002); 44 System.out.println(employee1); 45 46 } 47 48 //BiFunction中的R apply(T t,U u) 49 @Test 50 public void test3(){ 51 BiFunction<Integer,String,Employee> func1 = (id,name) -> new Employee(id,name); 52 System.out.println(func1.apply(1001,"Tom")); 53 54 55 BiFunction<Integer,String,Employee> func2 = Employee :: new; 56 System.out.println(func2.apply(1002,"Tom")); 57 58 } 59 60 //数组引用 61 //Function中的R apply(T t) 62 @Test 63 public void test4(){ 64 Function<Integer,String[]> func1 = length -> new String[length]; 65 String[] arr1 = func1.apply(5); 66 System.out.println(Arrays.toString(arr1)); 67 68 69 Function<Integer,String[]> func2 = String[] :: new; 70 String[] arr2 = func2.apply(10); 71 System.out.println(Arrays.toString(arr2)); 72 } 73 }
Stream
Stream的特点
1. Stream关注的是对数据的运算,与CPU打交道,集合关注的是数据的存储,与内存打交道。 2. Stream自己不会存储元素,不会改变源对象。相反,他们会返回一个持有结果的新Stream。 3. Stream操作是延迟执行的。这意味着他们会等到需要结果的时候才执行
Stream的创建
public class StreamAPITest { //创建 Stream方式一:通过集合 @Test public void test1(){ List<Employee> employees = EmployeeData.getEmployees(); // default Stream<E> stream() : 返回一个顺序流 Stream<Employee> stream = employees.stream(); // default Stream<E> parallelStream() : 返回一个并行流 Stream<Employee> parallelStream = employees.parallelStream(); } //创建 Stream方式二:通过数组 @Test public void test2(){ int[] arr = new int[]{1,2,3,4,5,6}; //调用Arrays类的static <T> Stream<T> stream(T[] array): 返回一个流 IntStream stream = Arrays.stream(arr); Employee e1 = new Employee(1001,"Tom"); Employee e2 = new Employee(1002,"Jerry"); Employee[] arr1 = new Employee[]{e1,e2}; Stream<Employee> stream1 = Arrays.stream(arr1); } //创建 Stream方式三:通过Stream的of() @Test public void test3(){ Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6); } //创建 Stream方式四:创建无限流 @Test public void test4(){ // 迭代 // public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f) //遍历前10个偶数 Stream.iterate(0, t -> t + 2).limit(10).forEach(System.out::println); // 生成 // public static<T> Stream<T> generate(Supplier<T> s) Stream.generate(Math::random).limit(10).forEach(System.out::println); } }
Stream的中间操作
public class StreamAPITest1 { //1-筛选与切片 @Test public void test1(){ List<Employee> list = EmployeeData.getEmployees(); //练习:查询员工表中薪资大于7000的员工信息 list.stream().filter(e -> e.getSalary() > 7000).forEach(System.out::println); // limit(n)——截断流,使其元素不超过给定数量。 list.stream().limit(3).forEach(System.out::println); // skip(n) —— 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补 list.stream().skip(3).forEach(System.out::println); // distinct()——筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素 list.add(new Employee(1010,"刘强东",40,8000)); list.add(new Employee(1010,"刘强东",41,8000)); list.add(new Employee(1010,"刘强东",40,8000)); list.stream().distinct().forEach(System.out::println); } //映射 @Test public void test2(){ // map(Function f)——接收一个函数作为参数,将元素转换成其他形式或提取信息,该函数会被应用到每个元素上,并将其映射成一个新的元素。 List<String> list = Arrays.asList("aa", "bb", "cc", "dd"); list.stream().map(str -> str.toUpperCase()).forEach(System.out::println); // 练习1:获取员工姓名长度大于3的员工的姓名。 List<Employee> employees = EmployeeData.getEmployees(); Stream<String> namesStream = employees.stream().map(Employee::getName); namesStream.filter(name -> name.length() > 3).forEach(System.out::println); //练习2: Stream<Stream<Character>> streamStream = list.stream().map(StreamAPITest1::fromStringToStream); streamStream.forEach(s ->{ s.forEach(System.out::println); }); // flatMap(Function f)——接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。 Stream<Character> characterStream = list.stream().flatMap(StreamAPITest1::fromStringToStream); characterStream.forEach(System.out::println); } //将字符串中的多个字符构成的集合转换为对应的Stream的实例 public static Stream<Character> fromStringToStream(String str){//aa ArrayList<Character> list = new ArrayList<>(); for(Character c : str.toCharArray()){ list.add(c); } return list.stream(); } //3-排序 @Test public void test4(){ // sorted()——自然排序 List<Integer> list = Arrays.asList(12, 43, 65, 34, 87, 0, -98, 7); list.stream().sorted().forEach(System.out::println); //抛异常,原因:Employee没有实现Comparable接口 List<Employee> employees1 = EmployeeData.getEmployees(); employees1.stream().sorted().forEach(System.out::println); // sorted(Comparator com)——定制排序 List<Employee> employees = EmployeeData.getEmployees(); employees.stream().sorted( (e1,e2) -> { int ageValue = Integer.compare(e1.getAge(),e2.getAge()); if(ageValue != 0){ return ageValue; }else{ return -Double.compare(e1.getSalary(),e2.getSalary()); } }).forEach(System.out::println); } }
Stream的终止操作
public class StreamAPITest2 { //1-匹配与查找 @Test public void test1(){ List<Employee> employees = EmployeeData.getEmployees(); // allMatch(Predicate p)——检查是否匹配所有元素。 // 练习:是否所有的员工的年龄都大于18 boolean allMatch = employees.stream().allMatch(e -> e.getAge() > 18); System.out.println(allMatch); // anyMatch(Predicate p)——检查是否至少匹配一个元素。 // 练习:是否存在员工的工资大于 10000 boolean anyMatch = employees.stream().anyMatch(e -> e.getSalary() > 10000); System.out.println(anyMatch); // noneMatch(Predicate p)——检查是否没有匹配的元素。 // 练习:是否存在员工姓“雷” boolean noneMatch = employees.stream().noneMatch(e -> e.getName().startsWith("雷")); System.out.println(noneMatch); // findFirst——返回第一个元素 Optional<Employee> employee = employees.stream().findFirst(); System.out.println(employee); // findAny——返回当前流中的任意元素 Optional<Employee> employee1 = employees.parallelStream().findAny(); System.out.println(employee1); } @Test public void test2(){ List<Employee> employees = EmployeeData.getEmployees(); // count——返回流中元素的总个数 long count = employees.stream().filter(e -> e.getSalary() > 5000).count(); System.out.println(count); // max(Comparator c)——返回流中最大值 // 练习:返回最高的工资: Stream<Double> salaryStream = employees.stream().map(e -> e.getSalary()); Optional<Double> maxSalary = salaryStream.max(Double::compare); System.out.println(maxSalary); // min(Comparator c)——返回流中最小值 // 练习:返回最低工资的员工 Optional<Employee> employee = employees.stream().min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())); System.out.println(employee); // forEach(Consumer c)——内部迭代 employees.stream().forEach(System.out::println); //使用集合的遍历操作 employees.forEach(System.out::println); } //2-归约 @Test public void test3(){ // reduce(T identity, BinaryOperator)——可以将流中元素反复结合起来,得到一个值。返回 T // 练习1:计算1-10的自然数的和 List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10); Integer sum = list.stream().reduce(0, Integer::sum); System.out.println(sum); // reduce(BinaryOperator) ——可以将流中元素反复结合起来,得到一个值。返回 Optional<T> // 练习2:计算公司所有员工工资的总和 List<Employee> employees = EmployeeData.getEmployees(); Stream<Double> salaryStream = employees.stream().map(Employee::getSalary); // Optional<Double> sumMoney = salaryStream.reduce(Double::sum); Optional<Double> sumMoney = salaryStream.reduce((d1,d2) -> d1 + d2); System.out.println(sumMoney.get()); } //3-收集 @Test public void test4(){ // collect(Collector c)——将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法 // 练习1:查找工资大于6000的员工,结果返回为一个List或Set // list List<Employee> employees = EmployeeData.getEmployees(); List<Employee> employeeList = employees.stream().filter(e -> e.getSalary() > 6000).collect(Collectors.toList()); employeeList.forEach(System.out::println); // set Set<Employee> employeeSet = employees.stream().filter(e -> e.getSalary() > 6000).collect(Collectors.toSet()); employeeSet.forEach(System.out::println); } }
Stream的通常用法:
@Test public void test(){ User u1 = User.builder().username("张三").age(18).build(); User u2 = User.builder().username("李四").age(20).build(); User u3 = User.builder().username("王五").age(19).build(); User u4 = User.builder().username("赵六").age(32).build(); User u5 = User.builder().username("赵六").age(33).build(); ArrayList<User> arry = new ArrayList<>(); arry.add(u1); arry.add(u2); arry.add(u3); arry.add(u4); arry.add(u5); /** * filter */ List<User> collect1 = arry.stream().filter(u -> u.getAge() > 18).collect(Collectors.toList()); /** * map */ // 匿名函数 List<String> collect2 = arry.stream().map(new Function<User, String>() { @Override public String apply(User user) { return user.getUsername(); } }).collect(Collectors.toList()); // lambda List<String> collect3 = arry.stream().map(u -> u.getUsername()).collect(Collectors.toList()); // 类::成员方法 List<String> collect4 = arry.stream().map(User::getUsername).collect(Collectors.toList()); List<User> collect5 = arry.stream().map(user -> user).collect(Collectors.toList()); List<Person> collect6 = arry.stream().map(user -> { Person p = new Person(); p.setAge(user.getAge()); p.setName(user.getUsername()); return p; }).collect(Collectors.toList()); /** * Collectors.toMap() */ // 注意:toMap的第三个参数没有会Duplicate key异常。产生这个问题的原因时我们参与转换的list中,作为key的属性有重复。(a,b)->a 表示保留先存进去的那个元素 Map<String, Integer> collect7 = arry.stream().collect(Collectors.toMap(User::getUsername, User::getAge, (a,b)->a)); // Function.identity() Map<String, User> collect8 = arry.stream().collect(Collectors.toMap(User::getUsername, Function.identity(),(a,b)->a)); // 同上 Map<String, User> collect9 = arry.stream().collect(Collectors.toMap(User::getUsername, u->u,(a,b)->a)); Map<User, String> collect10 = arry.stream().collect(Collectors.toMap(Function.identity(), User::getUsername)); /** * Collectors.groupingBy */ Map<Integer, List<User>> collect11 = arry.stream().collect(Collectors.groupingBy(User::getAge)); }
参考:
https://blog.csdn.net/qq_41107231/article/details/117426667
https://www.bilibili.com/video/BV184411x7XA?p=1

浙公网安备 33010602011771号