java8新特性【2023】
Lambda表达式
新的一套语法规则
是一个匿名函数
@Testpublic void test1(){Runnable r1 = new Runnable(){@Overridepublic void run() {System.out.println("线程A");}};r1.run();System.out.println("====================");Runnable r2 = () -> System.out.println("线程B");r2.run();}
public void test2(){//比大小Comparator<Integer> com1 = new Comparator<Integer>() {@Overridepublic int compare(Integer o1, Integer o2) {return Integer.compare(o1,o2);}};int i = com1.compare(15, 12);System.out.println(i);System.out.println("=======================");//比大小//函数式接口只有一个方法,就无需知道具体是哪个方法Comparator<Integer> com2 = (o1,o2) ->Integer.compare(o1,o2);int ii = com1.compare(15, 19);System.out.println(ii);}
方法引用
//比大小//函数式接口只有一个方法,就无需知道具体是哪个方法System.out.println("=======================");Comparator<Integer> com3 = Integer::compare;int iii = com1.compare(15, 15);System.out.println(iii);
格式【Lambda表达式的使用】分为8种
本质:作为接口的一个实例
public class LambdaTest1 {//11111无参无返回值的@Testpublic void test1(){Runnable r1 = new Runnable(){@Overridepublic void run() {System.out.println("线程A");}};r1.run();System.out.println("====================");Runnable r2 = () -> System.out.println("线程B");r2.run();}@Testpublic void test2() {//222222222222一个参数,但没有返回值Consumer<String> con = new Consumer<String>() {@Overridepublic void accept(String s) {System.out.println(s);}};con.accept("消费者");System.out.println("========================");//lambda的写法Consumer<String> conn = (String s) ->System.out.println(s);conn.accept("消费者11");}//33333333333数据类型可以省略,因为可以由编译器推断出来,称为"类型推断"@Testpublic void test3() {System.out.println("========================");//lambda的写法Consumer<String> conn1 = (s) ->System.out.println(s);conn1.accept("消费者22");}//444444444444444444若只需要一个参数时,参数的小括号可以省略@Testpublic void test4() {System.out.println("========================");//lambda的写法Consumer<String> conn1 = s ->System.out.println(s);conn1.accept("消费者33");}//555555555555555555555两个或以上的参数,多条执行行语句,并且可以有返回值@Testpublic void test5() {//lambda的写法//比大小Comparator<Integer> com1 = new Comparator<Integer>() {@Overridepublic int compare(Integer o1, Integer o2) {return Integer.compare(o1,o2);}};System.out.println("===========================");//比大小Comparator<Integer> com2 = new Comparator<Integer>() {@Overridepublic int compare(Integer o1, Integer o2) {System.out.println(o1);System.out.println(o2);return o1.compareTo(o2);}}; //比大小//66666666666System.out.println(com2.compare(15, 16));Comparator<Integer> com3 = (o1,o2) ->{System.out.println(o1);System.out.println(o2);return o1.compareTo(o2);};System.out.println(com3.compare(18, 12));}//7lambda只有一条语句,{}可以省略
}
函数式接口
只声明了一个抽样方法,则此接口就称为函数式接口
java四大核心函数式接口
Consumer<T>
:不返
Supplier<T>
:不给也返
Function<T,R>
R apply(T t)
Predicate<T>
:boolean test(T t)
方法引用与构造器引用
StreamAPI
对内存层面的多个数据,实现过滤,排序
可以对集合的数据进行操作,类似于sql执行的数据库查询
Stream操作三个步骤:创建----中间操作-------终止操作
创建:一个数据【如集合、数组】,获取一个流
中间操作:一个中间操作链,对数据源的数据进行处理
终止操作:一旦执行终止操作,就会执行中间操作链,并产生结果,之后不会被使用
创建Stream的方式
通过集合:
通过数组:
排序
自然排序:
List<Integer> list = Arrays.asList(12, 43, 65, 34, 87, 0, -98, 7);list.stream().sorted().forEach(System.out::println);
定制排序:
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());// 年龄相同,按工资从大到小排序// return -Double.compare(e1.getSalary(), e2.getSalary());}}).forEach(System.out::println);
创建无限流
Stream.iterate(0, t -> t + 2).limit(10).forEach(System.out::println);
Stream.generate(Math::random).limit(10).forEach(System.out::println);
筛选与切片
筛选
Stream<Employee> stream = list.stream();// 练习:查询员工表中薪资大于 7000 的员工信息stream.filter(e -> e.getSalary() > 7000).forEach(System.out::println);
// 1-筛选与切片@Testpublic void test5() {List<Employee> list = EmployeeData.getEmployees();// filter(Predicate p)-接收 Lambda,从流中排除某些元素。Stream<Employee> stream = list.stream();// 练习:查询员工表中薪资大于 7000 的员工信息stream.filter(e -> e.getSalary() > 7000).forEach(System.out::println);// Employee{id=1002, name='马云', age=12, salary=9876.12}// Employee{id=1004, name='雷军', age=26, salary=7657.37}// Employee{id=1006, name='比尔盖茨', age=42, salary=9500.43}System.out.println();// limit(n)-截断流,使其元素不超过给定数量。// stream.limit(3).forEach(System.out::println);//closed已经关闭,需要重新生成list.stream().limit(3).forEach(System.out::println);// Employee{id=1001, name='马化腾', age=34, salary=6000.38}// Employee{id=1002, name='马云', age=12, salary=9876.12}// Employee{id=1003, name='刘强东', age=33, salary=3000.82}System.out.println();// skip(n)-跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则list.stream().skip(3).forEach(System.out::println);// Employee{id=1004, name='雷军', age=26, salary=7657.37}// Employee{id=1005, name='李彦宏', age=65, salary=5555.32}// Employee{id=1006, name='比尔盖茨', age=42, salary=9500.43}// Employee{id=1007, name='任正非', age=26, salary=4333.32}// Employee{id=1008, name='扎克伯格', age=35, salary=2500.32}System.out.println();// distinct()-筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素list.add(new Employee(1010, "刘强东", 40, 8000));list.add(new Employee(1010, "刘强东", 42, 8000));list.add(new Employee(1010, "刘强东", 40, 8000));list.add(new Employee(1010, "刘强东", 40, 8000));list.add(new Employee(1010, "刘强东", 40, 8000));// System.out.println(list);// [Employee{id=1001, name='马化腾', age=34, salary=6000.38}, Employee{id=1002, name='马云', age=12, salary=9876.12},// Employee{id=1003, name='刘强东', age=33, salary=3000.82}, Employee{id=1004, name='雷军', age=26, salary=7657.37},// Employee{id=1005, name='李彦宏', age=65, salary=5555.32}, Employee{id=1006, name='比尔盖茨', age=42,// salary=9500.43}, Employee{id=1007, name='任正非', age=26, salary=4333.32}, Employee{id=1008, name='扎克伯格',// age=35, salary=2500.32}, Employee{id=1010, name='刘强东', age=40, salary=8000.0}, Employee{id=1010, name='刘强东',// age=42, salary=8000.0}, Employee{id=1010, name='刘强东', age=40, salary=8000.0}, Employee{id=1010, name='刘强东',// age=40, salary=8000.0}, Employee{id=1010, name='刘强东', age=40, salary=8000.0}]System.out.println("=================");list.stream().distinct().forEach(System.out::println);// Employee{id=1001, name='马化腾', age=34, salary=6000.38}// Employee{id=1002, name='马云', age=12, salary=9876.12}// Employee{id=1003, name='刘强东', age=33, salary=3000.82}// Employee{id=1004, name='雷军', age=26, salary=7657.37}// Employee{id=1005, name='李彦宏', age=65, salary=5555.32}// Employee{id=1006, name='比尔盖茨', age=42, salary=9500.43}// Employee{id=1007, name='任正非', age=26, salary=4333.32}// Employee{id=1008, name='扎克伯格', age=35, salary=2500.32}// Employee{id=1010, name='刘强东', age=40, salary=8000.0}// Employee{id=1010, name='刘强东', age=42, salary=8000.0}}
去重
list.stream().distinct().forEach(System.out::println);
映射
小写变大写
List<String> list = Arrays.asList("aa", "bb", "cc", "dd");list.stream().map(str -> str.toUpperCase()).forEach(System.out::println);
Stream终止操作
输出结果forEach(System.out::println);
Stream的终止操作:匹配与查询
匹配所有
@Testpublic void test9(){List<Employee> employees = EmployeeData.getEmployees();boolean allMatch = employees.stream().allMatch(e->e.getAge()>18);System.out.println(allMatch);}
有一个匹配就可以
List<Employee> employees1 = EmployeeData.getEmployees();boolean allMatch1 = employees1.stream().anyMatch(e->e.getAge()>18);System.out.println(allMatch1);
求个数
最大值
最小值
并行流
把一个内容分成多个数据模块,并用不同的线程分别处理每个数据块的流,相比较串行流,并行流可以很大层度上提高程序的执行效率
Optional类
最大化的减少空指针异常
新的时间日期API
其他特性
学习过程全部操作
public class LambdaTest2 {// 创建 Stream 方式一:通过集合@Testpublic 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 方式二:通过数组@Testpublic 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()@Testpublic void test3() {Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);}// 创建 Stream 方式四:创建无限流@Testpublic 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);}// 1-筛选与切片@Testpublic void test5() {List<Employee> list = EmployeeData.getEmployees();// filter(Predicate p)-接收 Lambda,从流中排除某些元素。Stream<Employee> stream = list.stream();// 练习:查询员工表中薪资大于 7000 的员工信息stream.filter(e -> e.getSalary() > 7000).forEach(System.out::println);// Employee{id=1002, name='马云', age=12, salary=9876.12}// Employee{id=1004, name='雷军', age=26, salary=7657.37}// Employee{id=1006, name='比尔盖茨', age=42, salary=9500.43}System.out.println("1");// limit(n)-截断流,使其元素不超过给定数量。// stream.limit(3).forEach(System.out::println);//closed已经关闭,需要重新生成list.stream().limit(3).forEach(System.out::println);System.out.println("/2");// skip(n)-跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则list.stream().skip(3).forEach(System.out::println);System.out.println();// distinct()-筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素list.add(new Employee(1010, "刘强东", 40, 8000));list.add(new Employee(1010, "刘强东", 42, 8000));list.add(new Employee(1010, "刘强东", 40, 8000));list.add(new Employee(1010, "刘强东", 40, 8000));list.add(new Employee(1010, "刘强东", 40, 8000));System.out.println("=================");list.stream().distinct().forEach(System.out::println);}// 映射@Testpublic void test6() {// map(Function f)-接收一个函数作为参数,将元素转换成其他形式或提取信息,该函数会被应用到每个元素上,并将其映射成一个新的元素。List<String> list = Arrays.asList("aa", "bb", "cc", "dd");list.stream().map(str -> str.toUpperCase()).forEach(System.out::println);System.out.println("===--=-=-==0-");// 练习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);System.out.println();// 练习2:Stream<Stream<Character>> streamStream = list.stream().map(LambdaTest2::fromStringToStream);streamStream.forEach(s -> {s.forEach(System.out::println);});System.out.println();// 集合里面套集合的方式,遍历优先使用 flatMap 方式// flatMap(Function f)-接受一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。Stream<Character> characterStream = list.stream().flatMap(LambdaTest2::fromStringToStream);characterStream.forEach(System.out::println);// a// a// b// b// c// c// d// d}// 将字符串中的多个字符构成的集合转换为对应的 Stream 的实例public static Stream<Character> fromStringToStream(String str) {// aArrayList<Character> list = new ArrayList<>();for (Character c : str.toCharArray()) {list.add(c);}return list.stream();}@Testpublic void test7() {ArrayList list1 = new ArrayList();list1.add(1);list1.add(2);list1.add(3);ArrayList list2 = new ArrayList();list2.add(4);list2.add(5);list2.add(6);list1.addAll(list2);System.out.println(list1);}// 3-排序@Testpublic void test8() {// sorted()-自然排序List<Integer> list = Arrays.asList(12, 43, 65, 34, 87, 0, -98, 7);list.stream().sorted().forEach(System.out::println);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());// 年龄相同,按工资从大到小排序// return -Double.compare(e1.getSalary(), e2.getSalary());}}).forEach(System.out::println);}
}