jdk8新特性

快来打我* 2024-03-30 10:54 217阅读 0赞

一、lambda表达式

Lambda表达式相当于是对接口抽象方法的重写

对比匿名内部类与lambda表达式
  1. package com.bz.jdk8.demo01_Lambda;
  2. /**
  3. * 体验Lambda表达式
  4. */
  5. public class Demo01LambdaIntro {
  6. public static void main(String[] args) {
  7. // 使用匿名内部类存在的问题
  8. // public Thread(Runnable target)
  9. // 匿名内部类做了哪些事情
  10. // 1.定义了一个没有名字的类
  11. // 2.这个类实现了Runnable接口
  12. // 3.创建了这个类的对象
  13. // 使用匿名内部类语法是很冗余的
  14. // 其实我们最关注的是run方法和里面要执行的代码.
  15. // Lambda表达式体现的是函数式编程思想,只需要将要执行的代码放到函数中(函数就是类中的方法)
  16. // Lambda就是一个匿名函数, 我们只需要将要执行的代码放到Lambda表达式中即可
  17. new Thread(new Runnable() {
  18. @Override
  19. public void run() {
  20. System.out.println("执行一个线程");
  21. }
  22. }).start();
  23. // Lambda表达式的好处: 可以简化匿名内部类,让代码更加精简
  24. //使用Lambda表达式
  25. new Thread(()->{
  26. System.out.println("使用了Lambda表达式");
  27. }).start();
  28. }
  29. }
标准格式

()->{}

  1. package com.bz.jdk8.demo01_Lambda;
  2. /**
  3. * Lambda表达式的标准格式
  4. * ()->{}
  5. *
  6. * // 小结:Lambda表达式相当于是对接口抽象方法的重写
  7. */
  8. public class Demo02LambdaUse {
  9. public static void main(String[] args) {
  10. goSwimming(new Swimmable() {
  11. @Override
  12. public void swimming() {
  13. System.out.println("练习无参数无返回值的匿名内部类");
  14. }
  15. });
  16. System.out.println("===============");
  17. goSwimming(()-> System.out.println("练习无参数无返回值的Lambda"));
  18. }
  19. // 练习无参数无返回值的Lambda
  20. public static void goSwimming(Swimmable s) {
  21. s.swimming();
  22. }
  23. }
省略写法

在Lambda标准格式的基础上,使用省略写法的规则为:

  1. 小括号内参数的类型可以省略。
  2. 如果小括号内有且仅有一个参数,则小括号可以省略。
  3. 如果大括号内有且仅有一个语句,可以同时省略大括号、return关键字及语句分号。
Lambda表达式的前提条件

Lambda表达式的前提条件:

  1. 方法的参数或变量的类型是接口。
  2. 这个接口中只能有一个抽象方法。

    package com.bz.jdk8.demo01_Lambda;

    /**

    • Lambda表达式的前提条件:
      1. 方法的参数或变量的类型是接口
      1. 这个接口中只能有一个抽象方法
        *
    • @FunctionalInterface // 检测这个接口是不是只有一个抽象方法
      */
      public class Demo04LambdaCondition {

      public static void main(String[] args) {

  1. test(()-> System.out.println("吃饭了吗?"));
  2. System.out.println("===========");
  3. Flyable f = ()->{
  4. System.out.println("飞呀飞。。。");
  5. };
  6. }
  7. public static void test(Flyable flyable){
  8. System.out.println("使用了lambda表达式");
  9. }
  10. }
  11. // 只有一个抽象方法的接口称为函数式接口,我们就能使用Lambda
  12. @FunctionalInterface // 检测这个接口是不是只有一个抽象方法
  13. interface Flyable {
  14. // 接口中有且仅有一个抽象方法
  15. public abstract void eat();
  16. // public abstract void eat2();
  17. }

二、接口增加默认方法和静态方法

接口引入默认方法的背景

如果给接口新增抽象方法,所有实现类都必须重写这个抽象方法。
不利于接口的扩展。

  1. package com.bz.jdk8.demo02interfaceupgrade;
  2. /**
  3. * 接口引入默认方法的背景
  4. * 在JDK 8以前接口中只能有抽象方法。存在以下问题:
  5. * 如果给接口新增抽象方法,所有实现类都必须重写这个抽象方法。
  6. * 不利于接口的扩展。
  7. */
  8. public class Demo01InterfaceDefaultIntro{
  9. }
  10. interface A {
  11. public abstract void test01();
  12. // 接口新增抽象方法,所有实现类都需要去重写这个方法,非常不利于接口的扩展
  13. // public abstract void test02();
  14. }
  15. class B implements A {
  16. @Override
  17. public void test01() {
  18. System.out.println("B test01");
  19. }
  20. }
  21. class C implements A {
  22. @Override
  23. public void test01() {
  24. System.out.println("C test01");
  25. }
  26. }
默认方法
  1. package com.bz.jdk8.demo02interfaceupgrade;
  2. /**
  3. * 接口默认方法的使用
  4. * 方式一:实现类直接调用接口默认方法
  5. * 方式二:实现类重写接口默认方法
  6. */
  7. public class Demo02UseDefaultFunction {
  8. public static void main(String[] args) {
  9. //方式一:实现类直接调用接口默认方法
  10. AA aa = new BB();
  11. aa.test1();
  12. System.out.println("===========");
  13. //方式二:实现类重写接口默认方法
  14. AA ac = new CC();
  15. ac.test1();
  16. }
  17. }
  18. interface AA{
  19. default void test1(){
  20. System.out.println("jdk8新增的默认的方法");
  21. }
  22. }
  23. class BB implements AA{
  24. //不重写方法
  25. }
  26. class CC implements AA{
  27. @Override
  28. public void test1() {
  29. System.out.println("重写了方法");
  30. }
  31. }
静态方法
  1. package com.bz.jdk8.demo02interfaceupgrade;
  2. /**
  3. * 接口的静态方法
  4. * 接口静态方法的使用
  5. * 直接使用接口名调用即可:接口名.静态方法名();
  6. *
  7. * 接口默认方法和静态方法的区别
  8. * 1. 默认方法通过实例调用,静态方法通过接口名调用。
  9. * 2. 默认方法可以被继承,实现类可以直接使用接口默认方法,也可以重写接口默认方法。
  10. * 3. 静态方法不能被继承,实现类不能重写接口静态方法,只能使用接口名调用。
  11. *
  12. * 如何选择呢?如果这个方法需要被实现类继承或重写,使用默认方法; 如果接口中的方法不需要被继承就使用静态方法
  13. */
  14. public class Demo03UseStaticFunction {
  15. public static void main(String[] args) {
  16. DD dd = new EE();
  17. //
  18. //通过接口名调用
  19. DD.test();
  20. }
  21. }
  22. interface DD{
  23. public static void test(){
  24. System.out.println("jdk8新增的静态方法");
  25. }
  26. }
  27. //无法重写静态方法
  28. class EE implements DD{
  29. // @Override
  30. // test
  31. }

接口默认方法和静态方法的区别

  1. 默认方法通过实例调用,静态方法通过接口名调用。
  2. 默认方法可以被继承,实现类可以直接使用接口默认方法,也可以重写接口默认方法。
  3. 静态方法不能被继承,实现类不能重写接口静态方法,只能使用接口名调用。

如何选择呢?如果这个方法需要被实现类继承或重写,使用默认方法; 如果接口中的方法不需要被继承就使用静态方法。

三、函数式接口

内置函数式接口的由来

我们知道使用Lambda表达式的前提是需要有函数式接口。而Lambda使用时不关心接口名,抽象方法名,只关心抽象方法的参数列表和返回值类型。因此为了让我们使用Lambda方便,JDK提供了大量常用的函数式接口。

Supplier接口

java.util.function.Supplier 接口,它意味着”供给” , 对应的Lambda表达式需要“对外提供”一个符合泛型类型的对象数据。

  1. package com.bz.jdk8.demo03functionalinterface;
  2. import java.util.Arrays;
  3. import java.util.function.Supplier;
  4. /**
  5. * java.util.function.Supplier<T> 接口,它意味着"供给" , 对应的Lambda表达式需要“对外提供”一个符合泛型类型的对象数据。
  6. * 供给型接口,通过Supplier接口中的get方法可以得到一个值,无参有返回的接口。
  7. */
  8. public class Demo02Supplier {
  9. // 使用Lambda表达式返回数组元素最大值
  10. public static void main(String[] args) {
  11. printMax(()->{
  12. int[] arr = new int[]{
  13. 23,25,11,56,45};
  14. Arrays.sort(arr);//升序
  15. return arr[arr.length - 1];
  16. });
  17. }
  18. public static void printMax(Supplier<Integer> supplier){
  19. System.out.println("supplier函数式接口");
  20. Integer max = supplier.get();
  21. System.out.println("max: "+max);
  22. }
  23. }
Consumer接口

java.util.function.Consumer 接口则正好相反,它不是生产一个数据,而是消费一个数据,其数据类型由泛型参数决定。

  1. package com.bz.jdk8.demo03functionalinterface;
  2. import java.util.function.Consumer;
  3. /**
  4. * java.util.function.Consumer<T> 接口则正好相反,它不是生产一个数据,而是消费一个数据,其数据类型由泛型参数决定。
  5. */
  6. public class Demo03Consumer {
  7. // 使用Lambda表达式将一个字符串转成大写的字符串
  8. public static void main(String[] args) {
  9. System.out.println("开始了");
  10. printHello((s)->{
  11. System.out.println(s.toUpperCase());
  12. });
  13. }
  14. public static void printHello(Consumer<String> consumer){
  15. System.out.println("consumer");
  16. consumer.accept("holle world");
  17. }
  18. }

默认方法:andThen
如果一个方法的参数和返回值全都是 Consumer 类型,那么就可以实现效果:消费一个数据的时候,首先做一个操作,然后再做一个操作,实现组合。而这个方法就是 Consumer 接口中的default方法 andThen 。

  1. package com.bz.jdk8.demo03functionalinterface;
  2. import java.util.function.Consumer;
  3. public class Demo04ConsumerAndThen {
  4. // 使用Lambda表达式先将一个字符串转成小写的字符串,再转成大写
  5. public static void main(String[] args) {
  6. System.out.println("开始啦");
  7. printHello((String str) -> {
  8. System.out.println(str.toLowerCase());
  9. }, (String str) -> {
  10. System.out.println(str.toUpperCase());
  11. });
  12. }
  13. public static void printHello(Consumer<String> c1, Consumer<String> c2) {
  14. System.out.println("aa");
  15. String str = "Hello World";
  16. // c1.accept(str);
  17. // c2.accept(str);
  18. c1.andThen(c2).accept(str);
  19. }
  20. }
Function接口

java.util.function.Function 接口用来根据一个类型的数据得到另一个类型的数据,前者称为前置条件,后者称为后置条件。有参数有返回值。

Function转换型接口,对apply方法传入的T类型数据进行处理,返回R类型的结果,有参有返回的接口。使用的场景例如:将 String 类型转换为 Integer

  1. package com.bz.jdk8.demo03functionalinterface;
  2. import java.util.function.Function;
  3. /**
  4. * Function接口
  5. * java.util.function.Function<T,R> 接口用来根据一个类型的数据得到另一个类型的数据,前者称为前置条件,
  6. * 后者称为后置条件。有参数有返回值。
  7. *
  8. * Function转换型接口,对apply方法传入的T类型数据进行处理,返回R类型的结果,有参有返回的接口。使用的场景
  9. * 例如:将 String 类型转换为 Integer 类型。
  10. */
  11. public class Demo05Function {
  12. // 使用Lambda表达式将字符串转成数字
  13. public static void main(String[] args) {
  14. System.out.println("开始了...");
  15. getNumber(str->{
  16. return Integer.parseInt(str);
  17. });
  18. }
  19. public static void getNumber(Function<String,Integer> function){
  20. System.out.println("输入字符串得到int数据");
  21. Integer apply = function.apply("98");
  22. System.out.println("num:"+apply);
  23. }
  24. }

默认方法:andThen
Function 接口中有一个默认的 andThen 方法,用来进行组合操作。

  1. package com.bz.jdk8.demo03functionalinterface;
  2. import java.util.function.Function;
  3. /**
  4. * 默认方法:andThen
  5. * Function 接口中有一个默认的 andThen 方法,用来进行组合操作。
  6. */
  7. public class Demo06FunctionAndThen {
  8. //第一个操作是将字符串解析成为int数字,第二个操作是乘以10。两个操作通过 andThen 按照前后顺序组合到了一起。
  9. public static void main(String[] args) {
  10. getNumber(str->{
  11. return Integer.parseInt(str);
  12. },i->{
  13. return i * 6;
  14. });
  15. }
  16. public static void getNumber(Function<String,Integer> f1,Function<Integer,Integer> f2){
  17. System.out.println("先转为int类型,如何再乘以6");
  18. /* Integer apply = f1.apply("5");
  19. Integer count = f2.apply(apply);*/
  20. Integer count = f1.andThen(f2).apply("5");
  21. System.out.println("结果:"+count);
  22. }
  23. }
Predicate接口

有时候我们需要对某种类型的数据进行判断,从而得到一个boolean值结果。这时可以使用java.util.function.Predicate 接口。

  1. package com.bz.jdk8.demo03functionalinterface;
  2. import java.util.function.Predicate;
  3. public class Demo07Predicate {
  4. // 使用Lambda判断一个人名如果超过3个字就认为是很长的名字
  5. public static void main(String[] args) {
  6. System.out.println("开始啦");
  7. isLongName((String name) -> {
  8. return name.length() > 3;
  9. });
  10. }
  11. public static void isLongName(Predicate<String> predicate) {
  12. System.out.println("aa");
  13. boolean isLong = predicate.test("迪丽热巴");
  14. System.out.println("是否是长名字: " + isLong);
  15. }
  16. }

默认方法:and,使用“与”逻辑实现“并且”的效果。
默认方法:or,实现逻辑关系中的“或”。
默认方法:negate,“非”(取反)。

  1. package com.bz.jdk8.demo03functionalinterface;
  2. import java.util.function.Predicate;
  3. public class Demo08Predicate_And_Or_Negate {
  4. // 使用Lambda表达式判断一个字符串中即包含W,也包含H
  5. // 使用Lambda表达式判断一个字符串中包含W或者包含H
  6. // 使用Lambda表达式判断一个字符串中不包含W
  7. public static void main(String[] args) {
  8. test((String str) -> {
  9. // 判断是否包含W
  10. return str.contains("W");
  11. }, (String str) -> {
  12. // 判断是否包含H
  13. return str.contains("H");
  14. });
  15. }
  16. public static void test(Predicate<String> p1, Predicate<String> p2) {
  17. // String str = "Hello orld";
  18. // boolean b1 = p1.test(str);
  19. // boolean b2 = p2.test(str);
  20. // if (b1 && b2) {
  21. // System.out.println("即包含W,也包含H");
  22. // }
  23. // 使用Lambda表达式判断一个字符串中即包含W,也包含H
  24. String str = "Hello World";
  25. boolean b = p1.and(p2).test(str);
  26. if (b) {
  27. System.out.println("即包含W,也包含H");
  28. }
  29. // 使用Lambda表达式判断一个字符串中包含W或者包含H
  30. boolean b1 = p1.or(p2).test(str);
  31. if (b1) {
  32. System.out.println("包含W或者包含H");
  33. }
  34. // 使用Lambda表达式判断一个字符串中不包含W
  35. boolean b2 = p1.negate().test("Hello W");
  36. // negate相当于取反 !boolean
  37. if (b2) {
  38. System.out.println("不包含W");
  39. }
  40. }
  41. }

四、方法引用

方法引用的格式

符号表示 ::

符号说明 : 双冒号为方法引用运算符,而它所在的表达式被称为方法引用。
应用场景 : 如果Lambda所要实现的方案 , 已经有其他方法存在相同方案,那么则可以使用方法引用,

  1. package com.bz.jdk8.demo04methodref;
  2. import java.sql.SQLOutput;
  3. import java.util.function.Consumer;
  4. /**
  5. * 方法引用的格式
  6. * 符号表示 : ::
  7. * * 符号说明 : 双冒号为方法引用运算符,而它所在的表达式被称为方法引用。
  8. * 应用场景 : 如果Lambda所要实现的方案 , 已经有其他方法存在相同方案,那么则可以使用方法引用
  9. */
  10. public class Demo01MethodRefIntro {
  11. public static void printMax(Consumer<int[]> consumer) {
  12. int[] arr = {
  13. 11, 22, 33, 44, 55};
  14. consumer.accept(arr);
  15. }
  16. //求一个数组的和
  17. public static void getSum(int[] arr){
  18. int sum = 0;
  19. for (int i : arr){
  20. sum += i;
  21. }
  22. System.out.println("和:"+sum);
  23. }
  24. // 使用方法引用
  25. // 让这个指定的方法去重写接口的抽象方法,到时候调用接口的抽象方法就是调用传递过去的这个方法
  26. public static void main(String[] args) {
  27. // 使用Lambda表达式求一个数组的和
  28. /*printMax((int[] arr) -> {
  29. getMax(arr);
  30. });*/
  31. printMax(Demo01MethodRefIntro::getSum);
  32. }
  33. }

方法引用的注意事项:

  • 被引用的方法,参数要和接口中抽象方法的参数一样。
  • 当接口抽象方法有返回值时,被引用的方法也必须有返回值。

方法引用是对Lambda表达式符合特定情况下的一种缩写,它使得我们的Lambda表达式更加的精简,也可以理解为 Lambda表达式的缩写形式 , 不过要注意的是方法引用只能”引用”已经存在的方法!

对象名::引用成员方法
  1. /**
  2. *对象名::引用成员方法
  3. *
  4. *注意:方法引用有两个注意事项
  5. * 1.被引用的方法,参数要和接口中抽象方法的参数一样
  6. * 2.当接口抽象方法有返回值时,被引用的方法也必须有返回值
  7. */
  8. @Test
  9. public void test1(){
  10. Date now = new Date();
  11. Supplier<Long> supplier = ()->{
  12. return now.getTime();
  13. };
  14. Supplier<Long> sp = now::getTime;
  15. Long aLong = sp.get();
  16. System.out.println("时间:"+aLong);
  17. }
类名::静态方法
  1. /**
  2. *类名::静态方法
  3. */
  4. @Test
  5. public void test2(){
  6. Supplier<Long> supplier = ()->{
  7. return System.currentTimeMillis();
  8. };
  9. Supplier<Long> sup = System::currentTimeMillis;
  10. Long aLong = supplier.get();
  11. Long aLong1 = sup.get();
  12. System.out.println(aLong + "---"+aLong1);
  13. }
类名::实例方法
  1. /**
  2. *类名::实例方法
  3. */
  4. @Test
  5. public void test3(){
  6. /*Function<String, Integer> f1 = (String str) -> {
  7. return str.length();
  8. };*/
  9. // 类名::实例方法(注意:类名::类名::实例方法实际上会将第一个参数作为方法的调用者)
  10. Function<String, Integer> f1 = String::length;
  11. int length = f1.apply("hello");
  12. System.out.println("length = " + length);
  13. // BiFunction<String, Integer, String> f2 = String::substring;
  14. // 相当于这样的Lambda
  15. BiFunction<String, Integer, String> f2 = (String str, Integer index) -> {
  16. return str.substring(index);
  17. };
  18. String str2 = f2.apply("helloworld", 3);
  19. System.out.println("str2 = " + str2); // loworld
  20. }
类名::new引用类的构造器
  1. // 类名::new引用类的构造器
  2. @Test
  3. public void test04() {
  4. /*Supplier<Person> su1 = () -> {
  5. return new Person();
  6. };*/
  7. Supplier<Person> su1 = Person::new;
  8. Person person = su1.get();
  9. System.out.println("person = " + person);
  10. /*BiFunction<String, Integer, Person> bif = (String name, Integer age) -> {
  11. return new Person(name, age);
  12. };*/
  13. BiFunction<String, Integer, Person> bif = Person::new;
  14. Person p2 = bif.apply("凤姐", 18);
  15. System.out.println("p2 = " + p2);
  16. }
类型[]::new
  1. // 类型[]::new
  2. @Test
  3. public void test05() {
  4. /*Function<Integer, int[]> f1 = (Integer length) -> {
  5. return new int[length];
  6. };*/
  7. Function<Integer, int[]> f1 = int[]::new;
  8. int[] arr1 = f1.apply(10);
  9. System.out.println(Arrays.toString(arr1));
  10. }

五、Stream流

注意:Stream和IO流(InputStream/OutputStream)没有任何关系,请暂时忘记对传统IO流的固有印象!
Stream是流式思想,相当于工厂的流水线,对集合中的数据进行加工处理

体验集合操作数据的弊端

  1. package com.bz.jdk8.demo05stream;
  2. import java.util.ArrayList;
  3. import java.util.Arrays;
  4. import java.util.Collections;
  5. import java.util.List;
  6. /*
  7. 目标:体验集合操作数据的弊端
  8. 小结:
  9. 1.集合操作数据的弊端?
  10. 每个需求都要循环一次,还要搞一个新集合来装数据, 麻烦
  11. */
  12. public class Demo01Intro {
  13. public static void main(String[] args) {
  14. // 一个ArrayList集合中存储有以下数据:张无忌,周芷若,赵敏,张强,张三丰
  15. // 需求:1.拿到所有姓张的 2.拿到名字长度为3个字的 3.打印这些数据
  16. List<String> arr = new ArrayList<>();
  17. Collections.addAll(arr,"张无忌","周芷若","张强","张三丰");
  18. List<String> list = new ArrayList<>();
  19. // 1.拿到所有姓张的
  20. for (String str : arr){
  21. if (str.contains("张")){
  22. list.add(str);
  23. }
  24. }
  25. //拿到名字长度为3个字的
  26. List<String> three = new ArrayList<>();
  27. for (String str : arr){
  28. if (str.length() == 3){
  29. three.add(str);
  30. }
  31. }
  32. System.out.println(Arrays.toString(list.toArray()));
  33. System.out.println(Arrays.toString(three.toArray()));
  34. System.out.println("=================");
  35. //使用流
  36. arr.stream().filter(str->{
  37. return str.startsWith("张");
  38. }).filter(str->{
  39. return str.length() == 3;
  40. }).forEach(s -> System.out.println(s));
  41. }
  42. }

获取流

Collection 集合通过 stream 默认方法获取流
  1. package com.bz.jdk8.demo05stream;
  2. import java.util.*;
  3. import java.util.stream.Stream;
  4. /**
  5. * java.util.stream.Stream<T> 是JDK 8新加入的流接口。
  6. * 获取一个流非常简单,有以下几种常用的方式:
  7. * 所有的 Collection 集合都可以通过 stream 默认方法获取流;
  8. * Stream 接口的静态方法 of 可以获取数组对应的流。
  9. */
  10. public class Demo02GetStream {
  11. public static void main(String[] args) {
  12. // 方式1 : 根据Collection获取流
  13. // Collection接口中有一个默认的方法: default Stream<E> stream()
  14. List<String> list = new ArrayList<>();
  15. Stream<String> stream1 = list.stream();
  16. Set<String> set = new HashSet<>();
  17. Stream<String> stream2 = set.stream();
  18. Map<String, String> map = new HashMap<>();
  19. Stream<String> stream3 = map.keySet().stream();
  20. Stream<String> stream4 = map.values().stream();
  21. Stream<Map.Entry<String, String>> stream5 = map.entrySet().stream();
  22. }
  23. }
Stream中的静态方法of获取流
  1. // 方式2 : Stream中的静态方法of获取流
  2. // static<T> Stream<T> of(T... values)
  3. Stream<String> stream6 = Stream.of("aa", "bb", "cc");
  4. String[] strs = {
  5. "aa", "bb", "cc"};
  6. Stream<String> stream7 = Stream.of(strs);
  7. // 基本数据类型的数组行不行?不行的,会将整个数组看做一个元素进行操作.
  8. int[] arr = {
  9. 11, 22, 33};
  10. Stream<int[]> stream8 = Stream.of(arr);

stream方法分为:终结方法和函数拼接方法

  1. package com.bz.jdk8.demo05stream;
  2. import java.util.stream.Stream;
  3. /**
  4. * 我们学习了Stream的常用方法,我们知道Stream这些常用方法可以分成两类,
  5. * 终结方法,
  6. * 函数拼接方法
  7. *
  8. * Stream的3个注意事项:
  9. * 1. Stream只能操作一次
  10. * 2. Stream方法返回的是新的流
  11. * 3. Stream不调用终结方法,中间的操作不会执行
  12. */
  13. public class Demo03StreamNotice {
  14. public static void main(String[] args) {
  15. Stream<String> stream = Stream.of("aa", "bb", "cc");
  16. //stream只能操作一次
  17. // long count = stream.count();
  18. // long count1 = stream.count();// stream has already been operated upon or closed
  19. // Stream<String> limit = stream.limit(1);
  20. //
  21. // System.out.println("流是否相等:"+(stream == limit));//流是否相等:false
  22. //3. Stream不调用终结方法,中间的操作不会执行
  23. stream.filter(s->{
  24. System.out.println(s);
  25. return true;
  26. }).count();
  27. }
  28. }

常用方法

forEach 用来遍历流中的数据
  1. /**
  2. * forEach 用来遍历流中的数据
  3. * 该方法接收一个 Consumer 接口函数,会将每一个流元素交给该函数进行处理。
  4. */
  5. @Test
  6. public void testForEach() {
  7. List<String> one = new ArrayList<>();
  8. Collections.addAll(one, "迪丽热巴", "宋远桥", "苏星河", "老子", "庄子", "孙子");
  9. //lambda表达式遍历
  10. // one.stream().forEach(str-> System.out.println(str));
  11. //使用方法引用
  12. one.stream().forEach(System.out::println);
  13. }
count 方法来统计其中的元素个数
  1. /**
  2. * Stream流提供 count 方法来统计其中的元素个数
  3. * 该方法返回一个long值代表元素个数。
  4. */
  5. @Test
  6. public void testCount() {
  7. List<String> one = new ArrayList<>();
  8. Collections.addAll(one, "迪丽热巴", "宋远桥", "苏星河", "老子", "庄子", "孙子");
  9. long count = one.stream().count();
  10. System.out.println("总数:"+count);
  11. }
filter用于过滤数据,返回符合过滤条件的数据
  1. /**
  2. * filter用于过滤数据,返回符合过滤条件的数据
  3. * 可以通过 filter 方法将一个流转换成另一个子集流。
  4. *
  5. * 该接口接收一个 Predicate 函数式接口参数(可以是一个Lambda或方法引用)作为筛选条件。
  6. */
  7. @Test
  8. public void testFilter() {
  9. List<String> arr = new ArrayList<>();
  10. Collections.addAll(arr, "宋远桥", "苏星河", "老子", "庄子", "孙子");
  11. arr.stream().filter(str->str.length() == 3).forEach(System.out::println);//宋远桥,苏星河
  12. }
limit 方法可以对流进行截取,只取用前n个。
  1. /**
  2. *limit 方法可以对流进行截取,只取用前n个。
  3. * 参数是一个long型,如果集合当前长度大于参数则进行截取。否则不进行操作。
  4. */
  5. @Test
  6. public void testLimit() {
  7. List<String> one = new ArrayList<>();
  8. Collections.addAll(one, "迪丽热巴", "宋远桥", "苏星河", "老子", "庄子", "孙子");
  9. one.stream().limit(3).forEach(System.out::println);
  10. }
skip 方法跳过前几个元素,获取一个截取之后的新流
  1. /**
  2. * 如果希望跳过前几个元素,可以使用 skip 方法获取一个截取之后的新流:
  3. *
  4. * 如果流的当前长度大于n,则跳过前n个;否则将会得到一个长度为0的空流。
  5. */
  6. @Test
  7. public void testSkip() {
  8. List<String> one = new ArrayList<>();
  9. Collections.addAll(one, "迪丽热巴", "宋远桥", "苏星河", "老子", "庄子", "孙子");
  10. one.stream().skip(2).forEach(System.out::println);
  11. }
map 方法将流中的元素映射到另一个流中

该接口需要一个 Function 函数式接口参数,可以将当前流中的T类型数据转换为另一种R类型的流。

  1. /**
  2. * 如果需要将流中的元素映射到另一个流中,可以使用 map 方法。
  3. * 该接口需要一个 Function 函数式接口参数,可以将当前流中的T类型数据转换为另一种R类型的流。
  4. */
  5. @Test
  6. public void testMap() {
  7. Stream<String> original = Stream.of("11", "22", "33");
  8. // original.map(str->Integer.parseInt(str)).forEach(System.out::println);
  9. // 将Stream流中的字符串转成Integer
  10. //方法引用简化
  11. original.map(Integer::parseInt).forEach(System.out::println);
  12. }
sorted 方法将数据排序
  1. /**
  2. *如果需要将数据排序,可以使用 sorted 方法。
  3. *sorted 方法根据元素的自然顺序排序,也可以指定比较器排序
  4. */
  5. @Test
  6. public void testSorted() {
  7. // sorted(): 根据元素的自然顺序排序
  8. // sorted(Comparator<? super T> comparator): 根据比较器指定的规则排序
  9. Stream<Integer> stream = Stream.of(33, 22, 11, 55);
  10. // stream.sorted().forEach(System.out::println);
  11. //自定义排序规则
  12. stream.sorted((o1, o2) -> o2-o1).forEach(System.out::println);
  13. }
distinct 方法去除重复数据
  1. /**
  2. *如果需要去除重复数据,可以使用 distinct 方法。
  3. *
  4. * 自定义类型是根据对象的hashCode和equals来去除重复元素的。
  5. */
  6. @Test
  7. public void testDistinct() {
  8. Stream<Integer> stream = Stream.of(22, 33, 22, 11, 33);
  9. stream.distinct().forEach(System.out::println);
  10. Stream<String> streamStr = Stream.of("aa","bb","cc","bb");
  11. streamStr.distinct().forEach(System.out::println);
  12. System.out.println("===============");
  13. //自定义类型是根据对象的hashCode和equals来去除重复元素的。
  14. Stream<Person> streamPer = Stream.of(
  15. new Person("貂蝉", 18),
  16. new Person("杨玉环", 20),
  17. new Person("杨玉环", 20),
  18. new Person("西施", 16),
  19. new Person("西施", 16),
  20. new Person("王昭君", 25)
  21. );
  22. streamPer.distinct().forEach(System.out::println);
  23. }
Match 相关方法,判断数据是否匹配指定的条件
  1. /**
  2. *如果需要判断数据是否匹配指定的条件,可以使用 Match 相关方法。
  3. * allMatch: 元素是否全部满足条件
  4. * anyMatch: 元素是否任意有一个满足条件
  5. * noneMatch: 元素是否全部不满足条件
  6. */
  7. @Test
  8. public void testMatch() {
  9. Stream<Integer> stream = Stream.of(5, 3, 6, 1);
  10. //allMatch: 匹配所有元素,所有元素都需要满足条件
  11. // boolean all = stream.allMatch(i -> i > 0);
  12. // System.out.println("是否都大于0:"+all);
  13. //anyMatch: 匹配某个元素,只要有其中一个元素满足条件即可
  14. // boolean any = stream.anyMatch(i -> i > 5);
  15. // System.out.println("是否存在大于5的元素:"+any);
  16. //noneMatch: 匹配所有元素,所有元素都不满足条件
  17. boolean none = stream.noneMatch(i -> i < 0);
  18. System.out.println("是否都不满足:"+none);
  19. }
find 方法,要找到某些数据
  1. /**
  2. *如果需要找到某些数据,可以使用 find 相关方法。
  3. */
  4. @Test
  5. public void testFind() {
  6. Stream<Integer> stream = Stream.of(33, 11, 22, 5);
  7. //获取第一个元素
  8. // Optional<Integer> first = stream.findFirst();
  9. Optional<Integer> any = stream.findAny();
  10. System.out.println(any.get());
  11. }
max 和 min 方法,获取最大和最小值
  1. /**
  2. * 如果需要获取最大和最小值,可以使用 max 和 min 方法。
  3. */
  4. @Test
  5. public void testMax_Min() {
  6. Integer max = Stream.of(7, 5, 3, 8, 2, 6).max((o1, o2) -> o1 - o2).get();
  7. System.out.println("最大值:"+max);//最大值:8
  8. Integer min = Stream.of(7, 5, 3, 8, 2, 6).min((o1, o2) -> o1 - o2).get();
  9. System.out.println("最小值:"+min);//最小值:2
  10. }
reduce 方法将所有数据归纳得到一个数据
  1. /**
  2. * 如果需要将所有数据归纳得到一个数据,可以使用 reduce 方法。
  3. */
  4. @Test
  5. public void testReduce() {
  6. // T reduce(T identity, BinaryOperator<T> accumulator);
  7. // T identity: 默认值
  8. // BinaryOperator<T> accumulator: 对数据进行处理的方式
  9. // reduce如何执行?
  10. // 第一次, 将默认值赋值给x, 取出集合第一元素赋值给y
  11. // 第二次, 将上一次返回的结果赋值x, 取出集合第二元素赋值给y
  12. // 第三次, 将上一次返回的结果赋值x, 取出集合第三元素赋值给y
  13. // 第四次, 将上一次返回的结果赋值x, 取出集合第四元素赋值给y
  14. Integer reduce = Stream.of(4, 5, 3, 9).reduce(0, (x, y) -> {
  15. System.out.println("x:" + x + ", y: " + y);
  16. return x + y;
  17. });
  18. System.out.println("reduce:"+reduce);
  19. System.out.println("==============");
  20. //获取最大值
  21. Integer max = Stream.of(6,3,7,9).reduce(0,(x,y)->{
  22. return x > y ? x : y;
  23. });
  24. System.out.println("最大值:"+max);
  25. }

Stream流的map和reduce组合使用

  1. //Stream流的map和reduce组合使用
  2. @Test
  3. public void testMapReduce() {
  4. // 求出所有年龄的总和
  5. // 1.得到所有的年龄
  6. // 2.让年龄相加
  7. Integer totalAge = Stream.of(
  8. new Person("刘德华", 58),
  9. new Person("张学友", 56),
  10. new Person("郭富城", 54),
  11. new Person("黎明", 52))
  12. .map(Person::getAge).reduce(0, Integer::sum);
  13. System.out.println("totalAge = " + totalAge);
  14. // 找出最大年龄
  15. // 1.得到所有的年龄
  16. // 2.获取最大的年龄
  17. Integer maxAge = Stream.of(
  18. new Person("刘德华", 58),
  19. new Person("张学友", 56),
  20. new Person("郭富城", 54),
  21. new Person("黎明", 52))
  22. .map(Person::getAge)
  23. .reduce(0, Math::max);
  24. System.out.println("maxAge = " + maxAge);
  25. // 统计 a 出现的次数
  26. // 1 0 0 1 0 1
  27. Integer count = Stream.of("a", "c", "b", "a", "b", "a")
  28. .map(s -> {
  29. if (s == "a") {
  30. return 1;
  31. } else {
  32. return 0;
  33. }
  34. })
  35. .reduce(0, Integer::sum);
  36. System.out.println("count = " + count);
  37. }
mapToInt 方法,将Stream中的Integer类型数据转成int类型
  1. /**
  2. * 如果需要将Stream中的Integer类型数据转成int类型,可以使用 mapToInt 方法。
  3. */
  4. @Test
  5. public void testNumericStream() {
  6. // Integer占用的内存比int多,在Stream流操作中会自动装箱和拆箱
  7. Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
  8. // 把大于3的打印出来
  9. stream.filter(i -> i > 3).forEach(System.out::println);
  10. System.out.println("=========先将流中的Integer数据转成int,后续都是操作int类型=======");
  11. IntStream intStream = Stream.of(1, 2, 3, 4, 5).mapToInt(Integer::intValue);
  12. intStream.filter(i -> i > 3).forEach(System.out::println);
  13. }
concat方法将两个流合并成为一个流
  1. /**
  2. * 如果有两个流,希望合并成为一个流,那么可以使用 Stream 接口的静态方法 concat :
  3. *
  4. * 备注:这是一个静态方法,与 java.lang.String 当中的 concat 方法是不同的
  5. */
  6. @Test
  7. public void testContact() {
  8. Stream<String> streamA = Stream.of("张三");
  9. Stream<String> streamB = Stream.of("李四");
  10. // 合并成一个流
  11. Stream<String> newStream = Stream.concat(streamA, streamB);
  12. // 注意:合并流之后,不能操作之前的流啦.
  13. // streamA.forEach(System.out::println);
  14. newStream.forEach(System.out::println);
  15. }
综合案例
  1. package com.bz.jdk8.demo05stream;
  2. import java.util.ArrayList;
  3. import java.util.Collections;
  4. import java.util.List;
  5. import java.util.stream.Stream;
  6. /**
  7. * Stream综合案例
  8. * 现在有两个 ArrayList 集合存储队伍当若干集合存储队伍当中的多个成员姓名,要求使用传统的for循环(或增强for循环)依
  9. * 次进行以下操作步骤:
  10. * 1. 第一个队伍只要名字为3个字的成员
  11. * 2. 第一个队伍筛选之后只要前3个人
  12. * 3. 第二个队伍只要姓张的成员姓名;
  13. * 4. 第二个队伍筛选之后不要前2个人;
  14. * 5. 将两个队伍合并为一个队伍;
  15. * 6. 根据姓名创建 Person 对象;
  16. * 7. 打印整个队伍的Person对象信息。
  17. */
  18. public class Demo05 {
  19. public static void main(String[] args) {
  20. // 第一个队伍
  21. List<String> one = new ArrayList<>();
  22. Collections.addAll(one,"迪丽热巴", "宋远桥", "苏星河", "老子", "庄子", "孙子", "洪七公");
  23. // 第二个队伍
  24. List<String> two = new ArrayList<>();
  25. Collections.addAll(two,"古力娜扎", "张无忌", "张三丰", "赵丽颖", "张二狗", "张天爱", "张三");
  26. //1. 第一个队伍只要名字为3个字的成员姓名;
  27. //2. 第一个队伍筛选之后只要前3个人;
  28. Stream<String> streamA = one.stream().filter(str -> str.length() == 3).limit(3);
  29. //3. 第二个队伍只要姓张的成员姓名;
  30. //4. 第二个队伍筛选之后不要前2个人;
  31. Stream<String> streamB = two.stream().filter(str -> str.startsWith("张")).skip(2);
  32. //5. 将两个队伍合并为一个队伍;
  33. Stream<String> stream = Stream.concat(streamA,streamB);
  34. //6. 根据姓名创建 Person 对象;
  35. //7. 打印整个队伍的Person对象信息。
  36. stream.map(Person2::new).forEach(System.out::println);
  37. }
  38. }

收集Stream流中的结果

Stream流中的结果到集合中
  1. /**
  2. * 将流中数据收集到集合中
  3. * Stream流提供 collect 方法,其参数需要一个 java.util.stream.Collector<T,A, R> 接口对象来指定收集到哪
  4. * 种集合中。java.util.stream.Collectors 类提供一些方法,可以作为 Collector`接口的实例:
  5. */
  6. @Test
  7. public void testStreamToCollection() {
  8. Stream<String> stream = Stream.of("aa", "bb", "cc", "bb");
  9. //list集合
  10. // List<String> list = stream.collect(Collectors.toList());
  11. // System.out.println("list= "+list);
  12. //set集合
  13. // Set<String> set = stream.collect(Collectors.toSet());
  14. // System.out.println("set="+set);
  15. //收集到指定的集合中ArrayList
  16. // ArrayList<String> arrayList = stream.collect(Collectors.toCollection(ArrayList::new));
  17. // System.out.println("收集到指定的集合中ArrayList="+arrayList);
  18. //HashSet
  19. HashSet<String> hashSet = stream.collect(Collectors.toCollection(HashSet::new));
  20. System.out.println("hashSet="+hashSet);
  21. }
Stream流中的结果到数组中
  1. /**
  2. * Stream流中的结果到数组中
  3. * Stream提供 toArray 方法来将结果放到一个数组中,返回值类型是Object[]的:
  4. */
  5. @Test
  6. public void testStreamToArray() {
  7. Stream<String> stream = Stream.of("aa", "bb", "cc");
  8. // 转成Object数组不方便
  9. // Object[] objects = stream.toArray();
  10. // for (Object o : objects) {
  11. // System.out.println("o = " + o);
  12. // }
  13. // String[]
  14. String[] strings = stream.toArray(String[]::new);
  15. for (String string : strings) {
  16. System.out.println("string = " + string + ", 长度: " + string.length());
  17. }
  18. }
对流中数据进行聚合计算
  1. // 其他收集流中数据的方式(相当于数据库中的聚合函数)
  2. @Test
  3. public void testStreamToOther() {
  4. Stream<Student> studentStream = Stream.of(
  5. new Student("赵丽颖", 58, 95),
  6. new Student("杨颖", 56, 88),
  7. new Student("迪丽热巴", 56, 99),
  8. new Student("柳岩", 52, 77));
  9. // Optional<Student> max = studentStream.collect(Collectors.maxBy((s1, s2) -> s1.getSocre() - s2.getSocre()));
  10. // System.out.println("最大值: " + max.get());
  11. // Optional<Student> min = studentStream.collect(Collectors.minBy((o1, o2) -> o1.getSocre() - o2.getSocre()));
  12. // System.out.println("最小值:"+min);
  13. // Integer count = studentStream.collect(Collectors.summingInt(Student::getAge));
  14. // System.out.println("年龄总和:"+count);
  15. // 平均值
  16. // Double avg = studentStream.collect(Collectors.averagingInt(s -> s.getSocre()));
  17. // Double avg = studentStream.collect(Collectors.averagingInt(Student::getSocre));
  18. // System.out.println("平均值: " + avg);
  19. // 统计数量
  20. Long count = studentStream.collect(Collectors.counting());
  21. System.out.println("统计数量: " + count);
  22. }
对流中数据进行分组
  1. /**
  2. * 对流中数据进行分组
  3. * 当我们使用Stream流处理数据后,可以根据某个属性将数据分组:
  4. */
  5. @Test
  6. public void testGroup() {
  7. Stream<Student> studentStream = Stream.of(
  8. new Student("赵丽颖", 52, 95),
  9. new Student("杨颖", 56, 88),
  10. new Student("迪丽热巴", 56, 55),
  11. new Student("柳岩", 52, 33));
  12. //根据年龄分组
  13. // Map<Integer, List<Student>> ageGroup = studentStream.collect(Collectors.groupingBy(Student::getAge));
  14. //根据分数分组
  15. Map<String, List<Student>> socreGroup = studentStream.collect(Collectors.groupingBy(s -> {
  16. if (s.getSocre() > 60) {
  17. return "及格";
  18. } else {
  19. return "不及格";
  20. }
  21. }));
  22. socreGroup.forEach((k,v)-> System.out.println(k + "::" +v));
  23. }
对流中数据进行多级分组
  1. // 多级分组
  2. @Test
  3. public void testCustomGroup() {
  4. Stream<Student> studentStream = Stream.of(
  5. new Student("赵丽颖", 52, 95),
  6. new Student("杨颖", 56, 88),
  7. new Student("迪丽热巴", 56, 55),
  8. new Student("柳岩", 52, 33));
  9. // 先根据年龄分组,每组中在根据成绩分组
  10. Map<Integer, Map<String, List<Student>>> map = studentStream.collect(Collectors.groupingBy(Student::getAge, Collectors.groupingBy((s) -> {
  11. if (s.getSocre() > 60) {
  12. return "及格";
  13. } else {
  14. return "不及格";
  15. }
  16. })));
  17. // 遍历
  18. map.forEach((k, v) -> {
  19. System.out.println(k);
  20. // v还是一个map,再次遍历
  21. v.forEach((k2, v2) -> {
  22. System.out.println("\t" + k2 + " == " + v2);
  23. });
  24. });
  25. }
对流中数据进行分区
  1. // 分区
  2. @Test
  3. public void testPartition() {
  4. Stream<Student> studentStream = Stream.of(
  5. new Student("赵丽颖", 52, 95),
  6. new Student("杨颖", 56, 88),
  7. new Student("迪丽热巴", 56, 55),
  8. new Student("柳岩", 52, 33));
  9. Map<Boolean, List<Student>> map = studentStream.collect(Collectors.partitioningBy(s -> {
  10. return s.getSocre() > 60;
  11. }));
  12. map.forEach((k,v)-> System.out.println(k + "=="+v));
  13. }
对流中数据进行拼接
  1. // 拼接
  2. @Test
  3. public void testJoining() {
  4. Stream<Student> studentStream = Stream.of(
  5. new Student("赵丽颖", 52, 95),
  6. new Student("杨颖", 56, 88),
  7. new Student("迪丽热巴", 56, 99),
  8. new Student("柳岩", 52, 77));
  9. //姓名使用_拼接
  10. // String name = studentStream.map(Student::getName).collect(Collectors.joining("_"));
  11. // System.out.println(name); //赵丽颖_杨颖_迪丽热巴_柳岩
  12. // 根据三个字符串拼接
  13. String name = studentStream.map(Student::getName).collect(Collectors.joining("_", "^_^", "V_V"));
  14. System.out.println(name);//^_^赵丽颖_杨颖_迪丽热巴_柳岩V_V
  15. }

并行的Stream流

串行的Stream流
  1. @Test
  2. public void test0Serial() {
  3. Stream.of(4, 5, 3, 9, 1, 2, 6)
  4. .filter(s -> {
  5. System.out.println(Thread.currentThread() + "::" + s);
  6. return s > 3;
  7. }).count();
  8. }
获取并行Stream流的两种方式
  1. 直接获取并行的流
  2. 将串行流转成并行流

    @Test

    1. public void testgetParallelStream() {
    2. // 掌握获取并行Stream流的两种方式
    3. // 方式一:直接获取并行的Stream流
    4. List<String> list = new ArrayList<>();
    5. Stream<String> stream = list.parallelStream();
    6. // 方式二:将串行流转成并行流
    7. Stream<String> parallel = list.stream().parallel();
    8. }
并行和串行Stream流的效率对比
  1. private static final int times = 500000000;
  2. long start;
  3. @Before
  4. public void init() {
  5. start = System.currentTimeMillis();
  6. }
  7. @After
  8. public void destory() {
  9. long end = System.currentTimeMillis();
  10. System.out.println("消耗时间:" + (end - start));
  11. }
  12. // 并行的Stream : 消耗时间:137 ---155
  13. @Test
  14. public void testParallelStream() {
  15. LongStream.rangeClosed(0, times).parallel().reduce(0, Long::sum);
  16. }
  17. // 串行的Stream : 消耗时间:343 ---210
  18. @Test
  19. public void testStream() {
  20. // 得到5亿个数字,并求和
  21. LongStream.rangeClosed(0, times).reduce(0, Long::sum);
  22. }
  23. // 使用for循环 : 消耗时间:235 ---164
  24. @Test
  25. public void testFor() {
  26. int sum = 0;
  27. for (int i = 0; i < times; i++) {
  28. sum += i;
  29. }
  30. }
parallelStream线程安全问题
  1. // parallelStream线程安全问题
  2. @Test
  3. public void parallelStreamNotice() {
  4. ArrayList<Integer> list = new ArrayList<>();
  5. /*IntStream.rangeClosed(1, 1000)
  6. .parallel()
  7. .forEach(i -> {
  8. list.add(i);
  9. });
  10. System.out.println("list = " + list.size());*/
  11. // 解决parallelStream线程安全问题方案一: 使用同步代码块
  12. /*Object obj = new Object();
  13. IntStream.rangeClosed(1, 1000)
  14. .parallel()
  15. .forEach(i -> {
  16. synchronized (obj) {
  17. list.add(i);
  18. }
  19. });*/
  20. // 解决parallelStream线程安全问题方案二: 使用线程安全的集合
  21. // Vector<Integer> v = new Vector();
  22. /*List<Integer> synchronizedList = Collections.synchronizedList(list);
  23. IntStream.rangeClosed(1, 1000)
  24. .parallel()
  25. .forEach(i -> {
  26. synchronizedList.add(i);
  27. });
  28. System.out.println("list = " + synchronizedList.size());*/
  29. // 解决parallelStream线程安全问题方案三: 调用Stream流的collect/toArray
  30. List<Integer> collect = IntStream.rangeClosed(1, 1000)
  31. .parallel()
  32. .boxed()
  33. .collect(Collectors.toList());
  34. System.out.println("collect.size = " + collect.size());
  35. }

Fork/Join框架

parallelStream使用的是Fork/Join框架。Fork/Join框架自JDK 7引入。Fork/Join框架可以将一个大任务拆分为很多小任务来异步执行。

Fork/Join框架主要包含三个模块:

  1. 线程池:ForkJoinPool
  2. 任务对象:ForkJoinTask
  3. 执行任务的线程:ForkJoinWorkerThread

Fork/Join原理-分治法

ForkJoinPool主要用来使用分治法(Divide-and-Conquer Algorithm)来解决问题。典型的应用比如快速排序算法,ForkJoinPool需要使用相对少的线程来处理大量的任务。比如要对1000万个数据进行排序,那么会将这个任务分割成两个500万的排序任务和一个针对这两组500万数据的合并任务。以此类推,对于500万的数据也会做出同样的分割处理,到最后会设置一个阈值来规定当数据规模到多少时,停止这样的分割处理。比如,当元素的数量小于10时,会停止分割,转而使用插入排序对它们进行排序。那么到最后,所有的任务加起来会有大概2000000+个。问题的关键在于,对于一个任务而言,只有当它所有的子任务完成之后,它才能够被执行。

Fork/Join原理-工作窃取算法

Fork/Join最核心的地方就是利用了现代硬件设备多核,在一个操作时候会有空闲的cpu,那么如何利用好这个空闲的cpu就成了提高性能的关键,而这里我们要提到的工作窃取(work-stealing)算法就是整个Fork/Join框架的核心理念Fork/Join工作窃取(work-stealing)算法是指某个线程从其他队列里窃取任务来执行。

  1. package com.bz.jdk8.demo05stream;
  2. import java.util.concurrent.ForkJoinPool;
  3. import java.util.concurrent.RecursiveTask;
  4. /**
  5. * Fork/Join框架介绍
  6. * parallelStream使用的是Fork/Join框架。
  7. *
  8. * Fork/Join框架可以将一个大任务拆分为很多小任务来异步执行。
  9. * Fork/Join框架主要包含三个模块:
  10. * 1. 线程池:ForkJoinPool
  11. * 2. 任务对象:ForkJoinTask
  12. * 3. 执行任务的线程:ForkJoinWorkerThread
  13. */
  14. public class Demo08ForkJoin {
  15. public static void main(String[] args) {
  16. long start = System.currentTimeMillis();
  17. ForkJoinPool pool = new ForkJoinPool();
  18. SumRecursiveTask task = new SumRecursiveTask(1, 99999999999L);
  19. Long result = pool.invoke(task);
  20. System.out.println("result = " + result);
  21. long end = System.currentTimeMillis();
  22. System.out.println("消耗时间: " + (end - start));
  23. }
  24. }
  25. // 1.创建一个求和的任务
  26. // RecursiveTask: 一个任务
  27. class SumRecursiveTask extends RecursiveTask<Long> {
  28. // 是否要拆分的临界值
  29. private static final long THRESHOLD = 3000L;
  30. // 起始值
  31. private final long start;
  32. // 结束值
  33. private final long end;
  34. public SumRecursiveTask(long start, long end) {
  35. this.start = start;
  36. this.end = end;
  37. }
  38. @Override
  39. protected Long compute() {
  40. long length = end - start;
  41. if (length < THRESHOLD) {
  42. // 计算
  43. long sum = 0;
  44. for (long i = start; i <= end; i++) {
  45. sum += i;
  46. }
  47. return sum;
  48. } else {
  49. // 拆分
  50. long middle = (start + end) / 2;
  51. SumRecursiveTask left = new SumRecursiveTask(start, middle);
  52. left.fork();
  53. SumRecursiveTask right = new SumRecursiveTask(middle + 1, end);
  54. right.fork();
  55. return left.join() + right.join();
  56. }
  57. }
  58. }

总结:

  1. parallelStream是线程不安全的。
  2. parallelStream适用的场景是CPU密集型的,只是做到别浪费CPU,假如本身电脑CPU的负载很大,那还到处用并行流,那并不能起到作用。
  3. I/O密集型 磁盘I/O、网络I/O都属于I/O操作,这部分操作是较少消耗CPU资源,一般并行流中不适用于I/O密集型的操作,就比如使用并流行进行大批量的消息推送,涉及到了大量I/O,使用并行流反而慢了很多。
  4. 在使用并行流的时候是无法保证元素的顺序的,也就是即使你用了同步集合也只能保证元素都正确但无法保证其中的顺序。

六、Optional类

Optional是一个没有子类的工具类,Optional是一个可以为null的容器对象。它的作用主要就是为了解决避免Null检查,防止NullPointerException。

  1. package com.bz.jdk8.demo06optional;
  2. import org.junit.Test;
  3. import java.util.Optional;
  4. /**
  5. * Optional是一个没有子类的工具类,Optional是一个可以为null的容器对象。
  6. * 它的作用主要就是为了解决避免Null检查,防止NullPointerException。
  7. */
  8. public class Demo01 {
  9. public static void main(String[] args) {
  10. }
  11. @Test
  12. public void test05() {
  13. User u = new User("Hello", 18);
  14. // getUpperUserName1(u);
  15. Optional<User> op = Optional.of(u);
  16. System.out.println(getUpperUserName2(op));
  17. }
  18. // 定义一个方法将User中的用户名转成大写并返回
  19. // 使用Optional方式
  20. public String getUpperUserName2(Optional<User> op) {
  21. /*String upperName = op.map(u -> u.getUserName())
  22. .map(s -> s.toUpperCase())
  23. .orElse("null");*/
  24. String upperName = op.map(User::getUserName)
  25. .map(String::toUpperCase)
  26. .orElse("null");
  27. return upperName;
  28. }
  29. // 定义一个方法将User中的用户名转成大写并返回
  30. // 使用传统方式
  31. public String getUpperUserName1(User u) {
  32. if (u != null) {
  33. String userName = u.getUserName();
  34. if (userName != null) {
  35. return userName.toUpperCase();
  36. } else {
  37. return null;
  38. }
  39. } else {
  40. return null;
  41. }
  42. }
  43. // Optional类的基本使用
  44. @Test
  45. public void test02() {
  46. // 1.创建Optional对象
  47. // of:只能传入一个具体值,不能传入null
  48. // ofNullable: 既可以传入具体值,也可以传入null
  49. // empty: 存入的是null
  50. Optional<String> op1 = Optional.of("凤姐");
  51. // 2.isPresent: 判断Optional中是否有具体值, 有值返回true,没有值返回false
  52. // boolean present = op1.isPresent();
  53. // System.out.println("present = " + present);
  54. // 3.get: 获取Optional中的值,如果有值就返回值具体值,没有值就报错
  55. // System.out.println(op3.get());
  56. if (op1.isPresent()) {
  57. System.out.println(op1.get());
  58. } else {
  59. System.out.println("没有值");
  60. }
  61. }
  62. // 以前对null的处理方式
  63. @Test
  64. public void test01() {
  65. String userName = "凤姐";
  66. if (userName != null) {
  67. System.out.println("姓名为: " + userName);
  68. } else {
  69. System.out.println("姓名不存在");
  70. }
  71. }
  72. }

七、新的日期和时间 API

旧版日期时间 API 存在的问题

  1. 设计很差: 在java.util和java.sql的包中都有日期类,java.util.Date同时包含日期和时间,而java.sql.Date仅包含日期。此外用于格式化和解析的类在java.text包中定义。
  2. 非线程安全:java.util.Date 是非线程安全的,所有的日期类都是可变的,这是Java日期类最大的问题之一。
  3. 时区处理麻烦:日期类并不提供国际化,没有时区支持,因此Java引入了java.util.Calendar和java.util.TimeZone类,但他们同样存在上述所有的问题。

    package com.bz.jdk8.demo07newdatetimeapi;

    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;

    /**

    • 旧版日期时间 API 存在的问题
      1. 设计很差: 在java.util和java.sql的包中都有日期类,java.util.Date同时包含日期和时间,而java.sql.Date仅包
    • 含日期。此外用于格式化和解析的类在java.text包中定义。
      1. 非线程安全:java.util.Date 是非线程安全的,所有的日期类都是可变的,这是Java日期类最大的问题之一。
      1. 时区处理麻烦:日期类并不提供国际化,没有时区支持,因此Java引入了java.util.Calendar和
    • java.util.TimeZone类,但他们同样存在上述所有的问题。
      */
      public class Demo01 {

      public static void main(String[] args) {

      //设计不合理
      Date date = new Date(2022,9,23);
      System.out.println(date);//Mon Oct 23 00:00:00 GMT+08:00 3922

      // 2.时间格式化和解析是线程不安全的
      SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd”);

      for (int i = 0;i < 50;i++){

      new Thread(()->{

      1. Date now = null;
      2. try {
      3. now = sdf.parse("2022-12-10");
      4. } catch (ParseException e) {
      5. throw new RuntimeException(e);
      6. }
      7. System.out.println(now);

      }).start();
      }
      }
      }

JDK 8的日期和时间类
  1. @Test
  2. public void testLocalDate() {
  3. //日期格式,年月日
  4. LocalDate localDate = LocalDate.of(2022, 12, 20);
  5. System.out.println(localDate);//2022-12-20
  6. //获取当前的年,月,日
  7. LocalDate now = LocalDate.now();
  8. System.out.println(now.getYear());
  9. System.out.println(now.getMonthValue());
  10. System.out.println(now.getDayOfMonth());
  11. }
  12. /**
  13. * LocalTime: 表示时间,有时分秒
  14. */
  15. @Test
  16. public void testLocalTime() {
  17. LocalTime localTime = LocalTime.of(15, 43, 56);
  18. System.out.println(localTime);//15:43:56
  19. LocalTime now = LocalTime.now();
  20. System.out.println("当前时间:"+now);//当前时间:15:46:47.207
  21. System.out.println("时:"+now.getHour()+"分:"+now.getMinute()+"秒:"+now.getSecond()+"纳秒:"+now.getNano());//时:15分:46秒:47纳秒:207000000
  22. }
  23. /**
  24. * 日期时间
  25. */
  26. @Test
  27. public void testLocalDateTime() {
  28. LocalDateTime localDateTime = LocalDateTime.of(2022, 12, 20, 15, 48, 30);
  29. System.out.println(localDateTime);//2022-12-20T15:48:30
  30. LocalDateTime now = LocalDateTime.now();
  31. System.out.println("当前日期:"+now);//2022-12-20T15:50:30.465
  32. System.out.println("当前年:"+now.getYear());//当前年:2022
  33. System.out.println("当前时:"+now.getHour());//当前时:15
  34. }
  35. /**
  36. * 修改时间
  37. */
  38. @Test
  39. public void testLocalDateTime2() {
  40. LocalDateTime now = LocalDateTime.now();
  41. //修改时间
  42. LocalDateTime withYear = now.withYear(9102);
  43. System.out.println("修改后的时间:"+withYear);//修改后的时间:9102-12-20T15:54:55.656
  44. System.out.println(now == withYear);//false
  45. //增加或减去指定的时间,plus:增加 minus:减少
  46. System.out.println("增加了2年后:"+now.plusYears(2));//增加了2年后:2024-12-20T15:54:55.656
  47. System.out.println("减少了5个月:"+now.minusMonths(5));//减少了5个月:2022-07-20T15:54:55.656
  48. }
  49. /**
  50. * 比较时间
  51. */
  52. @Test
  53. public void testEquals() {
  54. LocalDateTime dateTime = LocalDateTime.of(2022, 12, 20, 16, 00, 00);
  55. LocalDateTime now = LocalDateTime.now();
  56. System.out.println("当前时间是否在指定时间之前:"+now.isBefore(dateTime));//当前时间是否在指定时间之前:true
  57. System.out.println("当前时间是否在指定时间之后:"+now.isAfter(dateTime));//当前时间是否在指定时间之后:false
  58. System.out.println("当前时间是否等于指定时间:"+now.isEqual(dateTime));//当前时间是否等于指定时间:false
  59. }
JDK 8的时间格式化与解析
  1. // 日期格式化
  2. @Test
  3. public void test04() {
  4. LocalDateTime now = LocalDateTime.now();
  5. DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分SS秒");
  6. String format = now.format(dtf);
  7. System.out.println("格式化后的日期:"+format);//格式化后的日期:2022年12月20日 16时04分12秒
  8. //解析
  9. for (int i = 0; i < 50; i++) {
  10. new Thread(()->{
  11. LocalDateTime parse = LocalDateTime.parse("2022年09月20 15时16分16秒", dtf);
  12. System.out.println("parse:"+parse);
  13. }).start();
  14. }
  15. }

这里解析错误:

Exception in thread “Thread-1” Exception in thread “Thread-13” Exception in thread “Thread-8” Exception in thread “Thread-6” Exception in thread “Thread-2” Exception in thread “Thread-15” Exception in thread “Thread-18” Exception in thread “Thread-11” Exception in thread “Thread-12” java.time.format.DateTimeParseException: Text ‘2022年09月20 15时16分16秒’ could not be parsed at index 10
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)

Instant 类,时间戳
  1. // 时间戳
  2. @Test
  3. public void test07() {
  4. // Instant内部保存了秒和纳秒,一般不是给用户使用的,而是方便我们程序做一些统计的.
  5. Instant now = Instant.now();
  6. System.out.println("Instant:"+now);//Instant:2022-12-20T08:13:24.426Z
  7. Instant plus = now.plusSeconds(20);
  8. System.out.println("plus:"+plus);//plus:2022-12-20T08:13:44.426Z
  9. Instant minusSeconds = now.minusSeconds(20);
  10. System.out.println("minus:"+minusSeconds);//minus:2022-12-20T08:13:04.426Z
  11. //得到纳秒
  12. long epochSecond = now.getEpochSecond();
  13. System.out.println("epoch:"+epochSecond);//epoch:1671524004
  14. }
JDK 8的计算日期时间差类
  1. // Duration/Period类: 计算日期时间差
  2. @Test
  3. public void test08() {
  4. LocalTime now = LocalTime.now();
  5. LocalTime localTime = LocalTime.of(16, 17, 20);
  6. Duration duration = Duration.between(now, localTime);
  7. System.out.println("相差的天数:"+duration.toDays());//相差的天数:0
  8. System.out.println("相差的小时数:"+duration.toHours());//相差的小时数:0
  9. System.out.println("相差的分钟数:"+duration.toMinutes());//相差的分钟数:-3
  10. System.out.println("相差的秒数:"+duration.toMillis());//相差的秒数:-218907
  11. System.out.println("================");
  12. // Period计算日期的距离
  13. LocalDate nowDate = LocalDate.now();
  14. LocalDate localDate = LocalDate.of(1998, 11, 14);
  15. // 让后面的时间减去前面的时间
  16. Period period = Period.between(localDate,nowDate);
  17. System.out.println("相差的年:" + period.getYears());//相差的年:24
  18. System.out.println("相差的月:" + period.getMonths());//相差的月:1
  19. System.out.println("相差的天:" + period.getDays());//相差的天:6
  20. }
JDK 8的时间校正器
  1. // TemporalAdjuster类:自定义调整时间
  2. @Test
  3. public void test09() {
  4. LocalDateTime now = LocalDateTime.now();
  5. // 将日期调整到“下一个月的第一天”操作。
  6. TemporalAdjuster firstDayOfNextMonth = temporal -> {
  7. // temporal要调整的时间
  8. LocalDateTime dateTime = (LocalDateTime)temporal;
  9. return dateTime.plusMonths(1).withDayOfMonth(1); // 下一个月的第一天
  10. };
  11. // JDK中自带了很多时间调整器
  12. // LocalDateTime newDateTime = now.with(firstDayOfNextMonth);
  13. LocalDateTime newDateTime = now.with(TemporalAdjusters.firstDayOfNextYear());
  14. System.out.println("newDateTime = " + newDateTime);//newDateTime = 2023-01-01T18:33:24.152
  15. }
JDK 8设置日期时间的时区
  1. // 设置日期时间的时区
  2. @Test
  3. public void test10() {
  4. // 1.获取所有的时区ID
  5. // ZoneId.getAvailableZoneIds().forEach(System.out::println);
  6. // 不带时间,获取计算机的当前时间
  7. LocalDateTime now = LocalDateTime.now(); // 中国使用的东八区的时区.比标准时间早8个小时
  8. System.out.println("now = " + now);
  9. // 2.操作带时区的类
  10. // now(Clock.systemUTC()): 创建世界标准时间
  11. ZonedDateTime bz = ZonedDateTime.now(Clock.systemUTC());
  12. System.out.println("bz = " + bz);
  13. // now(): 使用计算机的默认的时区,创建日期时间
  14. ZonedDateTime now1 = ZonedDateTime.now();
  15. System.out.println("now1 = " + now1); // 2019-10-19T16:19:44.007153500+08:00[Asia/Shanghai]
  16. // 使用指定的时区创建日期时间
  17. ZonedDateTime now2 = ZonedDateTime.now(ZoneId.of("America/Vancouver"));
  18. System.out.println("now2 = " + now2); // 2019-10-19T01:53:41.225898600-07:00[America/Vancouver]
  19. // 修改时区
  20. // withZoneSameInstant: 即更改时区,也更改时间
  21. ZonedDateTime withZoneSameInstant = now2.withZoneSameInstant(ZoneId.of("Asia/Shanghai"));
  22. System.out.println("withZoneSameInstant = " + withZoneSameInstant); // 2019-10-19T16:53:41.225898600+08:00[Asia/Shanghai]
  23. // withZoneSameLocal: 只更改时区,不更改时间
  24. ZonedDateTime withZoneSameLocal = now2.withZoneSameLocal(ZoneId.of("Asia/Shanghai"));
  25. System.out.println("withZoneSameLocal = " + withZoneSameLocal); // 2019-10-19T01:54:52.058871300+08:00[Asia/Shanghai]
  26. }

八、JDK 8重复注解与类型注解

重复注解的使用

自从Java 5中引入 注解 以来,注解开始变得非常流行,并在各个框架和项目中被广泛使用。不过注解有一个很大的限制是:在同一个地方不能多次使用同一个注解。JDK 8引入了重复注解的概念,允许在同一个地方多次使用同一个注解。在JDK 8中使用@Repeatable注解定义重复注解。

  1. package com.bz.jdk8.demo08annotation;
  2. import org.junit.Test;
  3. import java.lang.annotation.Repeatable;
  4. import java.lang.annotation.Retention;
  5. import java.lang.annotation.RetentionPolicy;
  6. /**
  7. * 配置重复注解
  8. * 自从Java 5中引入 注解 以来,注解开始变得非常流行,并在各个框架和项目中被广泛使用。不过注解有一个很大的限
  9. * 制是:在同一个地方不能多次使用同一个注解。JDK 8引入了重复注解的概念,允许在同一个地方多次使用同一个注
  10. * 解。在JDK 8中使用@Repeatable注解定义重复注解。
  11. */
  12. @MyTest("ta")
  13. @MyTest("tb")
  14. @MyTest("tc")
  15. public class Demo01 {
  16. @Test
  17. @MyTest("ma")
  18. @MyTest("mb")
  19. public void test() {
  20. }
  21. public static void main(String[] args) throws NoSuchMethodException {
  22. // 4.解析重复注解
  23. // 获取类上的重复注解
  24. // getAnnotationsByType是新增的API用户获取重复的注解
  25. MyTest[] annotationsByType = Demo01.class.getAnnotationsByType(MyTest.class);
  26. for (MyTest myTest : annotationsByType) {
  27. System.out.println(myTest);
  28. }
  29. System.out.println("----------");
  30. // 获取方法上的重复注解
  31. MyTest[] tests = Demo01.class.getMethod("test").getAnnotationsByType(MyTest.class);
  32. for (MyTest test : tests) {
  33. System.out.println(test);
  34. }
  35. }
  36. }
  37. // 1.定义重复的注解容器注解
  38. @Retention(RetentionPolicy.RUNTIME)
  39. @interface MyTests {
  40. // 这是重复注解的容器
  41. MyTest[] value();
  42. }
  43. // 2.定义一个可以重复的注解
  44. @Retention(RetentionPolicy.RUNTIME)
  45. @Repeatable(MyTests.class)
  46. @interface MyTest {
  47. String value();
  48. }
类型注解的使用

JDK 8为@Target元注解新增了两种类型: TYPE_PARAMETER , TYPE_USE 。
TYPE_PARAMETER :表示该注解能写在类型参数的声明语句中。
TYPE_USE :表示注解可以再任何用到类型的地方使用。

  1. package com.bz.jdk8.demo08annotation;
  2. import java.lang.annotation.ElementType;
  3. import java.lang.annotation.Target;
  4. import java.util.ArrayList;
  5. public class Demo02 <@TypeParam T> {
  6. private @NotNull int a = 10;
  7. public void test(@NotNull String str, @NotNull int a) {
  8. @NotNull double d = 10.1;
  9. }
  10. public <@TypeParam E extends Integer> void test01() {
  11. }
  12. }
  13. @Target(ElementType.TYPE_USE)
  14. @interface NotNull {
  15. }
  16. @Target(ElementType.TYPE_PARAMETER)
  17. @interface TypeParam {
  18. }

介绍!!


  1. 要散布阳光到别人心里,先得自己心里有阳光。 --罗曼罗兰

发表评论

表情:
评论列表 (有 0 条评论,217人围观)

还没有评论,来说两句吧...

相关阅读

    相关 JDK8特性

        一、default关键字     在java里面,我们通常都是认为接口里面是只能有抽象方法,不能有任何方法的实现的,那么在jdk1.8里面打破了这个规定,引入了新

    相关 jdk8特性

    在学习JDK8新特性Optional类的时候,提到对于Optional的两个操作映射和过滤设计到JDK提供的流式出来。这篇文章便详细的介绍流式处理: 一. 流式处理简介 流

    相关 JDK8 特性

    接口的默认方法只需要使用 default 关键字即可,这个特征又叫做 扩展方法 Lambda 表达式 Functional 接口 函数式接口 是指仅仅只包含一个抽象方法...