1 JavaSE的发展历史

1.1 Java语言的介绍

  • SUN公司在1991年成立了一个称为绿色计划(Green Project)的项目,由James Gosling(高斯林)博士领导,绿色计划的目的是开发一种能够在各种消费性电子产品(机顶盒、冰箱、收音机等)上运行的程序架构。这个项目的产品就是Java语言的前身:Oak(橡树)。Oak当时在消费品市场上并不算成功,但是随着1995年互联网潮流的兴起,Oak迅速找到了最适合自己发展的市场定位。

1.2 JDK的发展历史

  • JDK Beta - 1995。
  • JDK 1.0 - 1996年1月 (真正第一个稳定的版本JDK 1.0.2,被称为Java1)
  • JDK 1.1 - 1997年2月。
  • J2SE 1.2 - 1998年12月。
    • J2SE(Java 2 Standard Edition,Java 2平台的标准版),应用于桌面环境。
    • J2ME(Java 2 Micro Edition,Java 2平台的微型版),应用于移动、无线及有限资源的环境。
    • J2EE(Java 2 Enterprise Edition,Java 2平台的企业版),应用于基于Java的应用服务器。
  • J2SE 1.3 - 2000年5月。
  • J2SE 1.4 - 2002年2月。
  • J2SE 5.0 - 2004年9月。
  • Java SE 6 - 2006年12月。
  • Java SE 7 - 2011年7月。
  • Java SE 8 (LTS) - 2014年3月。
  • Java SE 9 - 2017年9月。
  • Java SE 10 (18.3) - 2018年3月。
  • Java SE 11 (18.9 LTS) - 2018年9月。
  • Java SE 12 (19.3) - 2019年3月。
  • Java SE 13 (19.9) - 2019年9月。
  • ……

2 了解Open JDK和Oracle JDK

2.1 Open JDK的来源

  • Java是由SUN公司发明,Open JDK是SUN在2006年末把Java开源而形成的项目。也就是说Open JDK是Java SE平台版的开源和免费实现,它是由SUN和Java社区提供支持,2009年Oracle收购了SUN公司,自此Java的维护方之一的SUN也变成了Oracle。

2.2 Open JDK和Oracle JDK的关系

  • 大多数的JDK都是在Open JDK的基础上进一步编写实现的,比如IBM J9、Oracle JDK等。
  • Oracle JDK完全是由Oracle公司开发,Oracle JDK是基于Open JDK源代码的商业版本。此外,它包含闭源组件。
  • Oracle JDK根据二进制代码许可协议获取许可,在没有商业许可的情况下,在2019年1月之后发布的Oracle JDK的公开更新将无法用于商业或生产用途。
  • Open JDK是完全开源的,可以自由使用。

Open JDK和Oracle JDK的关系.png

2.3 Open JDK官网介绍

  • Open JDK官网
  • JDK Enhancement Proposals(JDK增强建议)。通俗的讲JEP就是JDK的新特性。

2.4 总结

  • Oracle JDK是基于Open JDK源代码的商业版本。
  • 我们要学习Java新技术可以去Open JDK官网学习。

3 JDK8新特性

3.1 Lambda表达式的介绍

3.1.1 使用匿名内部类存在的问题

  • 当需要启动一个线程去完成任务的时候,通常会通过Runnable接口来定义任务内容,并使用Thread类来启动该线程。
  • 传统写法,代码如下:
  1. package com.sunxaiping.jdk8;
  2. public class LambdaDemo1 {
  3. public static void main(String[] args) {
  4. //使用匿名内部类存在的问题
  5. //匿名内部类做了哪些事情
  6. //①定义了一个没有名字的类
  7. //②这个类实现了Runnable接口
  8. //③创建了这个类的对象
  9. //其实我们最关注的是run方法和里面要执行的代码。
  10. //所以使用匿名内部类语法是很冗余的。
  11. new Thread(new Runnable() {
  12. @Override
  13. public void run() {
  14. System.out.println("线程执行啦(*^▽^*)");
  15. }
  16. }).start();
  17. }
  18. }
  • 由于面向对象的语法要求,首先创建一个Runnable接口的匿名类对象来指定线程要执行的任务内容,再将其交给一个线程来启动。
  • 代码分析:对于Runnable的匿名内部类用法,可以分析出以下几点内容:
    • JDK8 - 图2Thread类需要Runnable接口作为参数,其中的抽象方法run方法是用来指定线程任务内容的核心。
    • JDK8 - 图3为了指定run的方法体,不得不需要Runnable接口的实现类。
    • JDK8 - 图4为了省去定义个Runnable实现类的麻烦,不得不使用匿名内部类。
    • JDK8 - 图5必须覆盖重写run方法,所以方法名称,方法参数、方法返回值不得不重写一遍,且不能写错。
    • JDK8 - 图6实际上,似乎只有run方法体才是关键所在。

3.1.2 体验Lambda

  • Lambda是一个匿名函数,可以理解为一段可以传递的代码。
  • Lambda表达式写法,代码如下:
  1. package com.sunxaiping.jdk8;
  2. public class LambdaDemo2 {
  3. public static void main(String[] args) {
  4. //Lambda体现的是函数式编程思想,只需要将要执行的代码放到函数中(函数就是类中的方法)
  5. //Lambda就是一个匿名函数,我们只需要将要执行的代码放到Lambda表达式中即可
  6. //Lambda表达式的好处:可以简化匿名内部类,让代码更加精简。
  7. new Thread(() -> {
  8. System.out.println("线程执行啦(*^▽^*)");
  9. }).start();
  10. }
  11. }
  • 这段代码和使用内名内部类的执行效果是完全一样的,可以在JDK8或更高的编译级别下通过。从代码的语义中可以看出:我们启动了一个线程,而线程任务的内容以一种更加简洁的形式被指定。

3.1.3 Lambda的优点

  • 简化匿名内部类的使用,语法更加简单。

3.2 Lambda的标准格式

3.2.1 Lambda的标准格式

  • Lambda省去了面向对象的条条框框,Lambda的标准格式由3个部分组成:
  1. (参数类型 参数名称) -> {
  2. 代码体;
  3. }
  • 格式说明:
    • (参数类型 参数名称):参数列表。
    • {代码体;}:方法体。
    • ->:箭头,没有实际含义,起到连接的作用。

3.2.2 无参数无返回值的Lambda

  • 示例:
  1. package com.sunxaiping.jdk8;
  2. @FunctionalInterface
  3. public interface Swimmable {
  4. /**
  5. * 游泳
  6. */
  7. void swimming();
  8. }
  1. package com.sunxaiping.jdk8;
  2. /**
  3. * Lambda表达式的标准格式:
  4. * (参数列表)->{}
  5. * (参数列表):参数列表
  6. * {}:方法体
  7. * ->:没有实际含义,起到连接的作用
  8. */
  9. public class LambdaDemo3 {
  10. public static void main(String[] args) {
  11. goSwimming(new Swimmable() {
  12. @Override
  13. public void swimming() {
  14. System.out.println("我是匿名内部类的游泳");
  15. }
  16. });
  17. goSwimming(() -> {
  18. System.out.println("我是Lambda的游泳");
  19. });
  20. }
  21. /**
  22. * 无参数无返回值的Lambda
  23. *
  24. * @param swimmable
  25. */
  26. public static void goSwimming(Swimmable swimmable) {
  27. swimmable.swimming();
  28. }
  29. }

3.2.3 有参数有返回值的Lambda

  • 示例:
  1. package com.sunxaiping.jdk8;
  2. public interface Smokeable {
  3. int smoking(String name);
  4. }
  1. package com.sunxaiping.jdk8;
  2. /**
  3. * Lambda表达式的标准格式:
  4. * (参数列表)->{}
  5. * (参数列表):参数列表
  6. * {}:方法体
  7. * ->:没有实际含义,起到连接的作用
  8. */
  9. public class LambdaDemo4 {
  10. public static void main(String[] args) {
  11. goSmoking(new Smokeable() {
  12. @Override
  13. public int smoking(String name) {
  14. System.out.println("匿名内部类:抽了" + name + "的烟");
  15. return 0;
  16. }
  17. });
  18. goSmoking((String name) -> {
  19. System.out.println("Lambda:抽了" + name + "的烟");
  20. return 0;
  21. });
  22. }
  23. public static void goSmoking(Smokeable smokeable) {
  24. smokeable.smoking("中华");
  25. }
  26. }

3.2.4 总结

  • Lambda表达式的标准格式:
  1. (参数列表) -> {}
  • 以后我们看到调用的方法其参数是接口就可以考虑使用Lambda表达式来替代匿名内部类,但是不是所有的匿名内部类都能使用Lambda表达式来替代,Lambda表达式相当于对接口的抽象方法的重写。。

3.3 了解Lambda的实现原理

  • 示例:
  1. package com.sunxaiping.jdk8;
  2. @FunctionalInterface
  3. public interface Swimmable {
  4. /**
  5. * 游泳
  6. */
  7. void swimming();
  8. }
  1. package com.sunxaiping.jdk8;
  2. /**
  3. * Lambda表达式的标准格式:
  4. * (参数列表)->{}
  5. * (参数列表):参数列表
  6. * {}:方法体
  7. * ->:没有实际含义,起到连接的作用
  8. */
  9. public class LambdaDemo3 {
  10. public static void main(String[] args) {
  11. goSwimming(new Swimmable() {
  12. @Override
  13. public void swimming() {
  14. System.out.println("我是匿名内部类的游泳");
  15. }
  16. });
  17. }
  18. /**
  19. * 无参数无返回值的Lambda
  20. *
  21. * @param swimmable
  22. */
  23. public static void goSwimming(Swimmable swimmable) {
  24. swimmable.swimming();
  25. }
  26. }
  • 我们可以看到匿名内部类会在编译后产生一个类:LambdaDemo3$1.class。

匿名内部类会在编译后产生一个类.png

  • 使用XJad反编译这个类,得到如下的代码:
  1. // Decompiled by Jad v1.5.8e2. Copyright 2001 Pavel Kouznetsov.
  2. // Jad home page: http://kpdus.tripod.com/jad.html
  3. // Decompiler options: packimports(3) fieldsfirst ansi space
  4. // Source File Name: LambdaDemo3.java
  5. package com.sunxaiping.jdk8;
  6. import java.io.PrintStream;
  7. // Referenced classes of package com.sunxaiping.jdk8:
  8. // Swimmable, LambdaDemo3
  9. static class LambdaDemo3$1
  10. implements Swimmable
  11. {
  12. public void swimming()
  13. {
  14. System.out.println("我是匿名内部类的游泳");
  15. }
  16. LambdaDemo3$1()
  17. {
  18. }
  19. }
  • 我们再看Lambda的效果,修改代码如下:
  1. package com.sunxaiping.jdk8;
  2. /**
  3. * Lambda表达式的标准格式:
  4. * (参数列表)->{}
  5. * (参数列表):参数列表
  6. * {}:方法体
  7. * ->:没有实际含义,起到连接的作用
  8. */
  9. public class LambdaDemo3 {
  10. public static void main(String[] args) {
  11. goSwimming(()->{
  12. System.out.println("Lambda的游泳");
  13. });
  14. }
  15. /**
  16. * 无参数无返回值的Lambda
  17. *
  18. * @param swimmable
  19. */
  20. public static void goSwimming(Swimmable swimmable) {
  21. swimmable.swimming();
  22. }
  23. }

Lambda产生的效果.png

  • 运行程序,控制台得到预期的结果,但是并没有出现一个新的类,也就是说Lambda并没有在编译的时候产生新的类。使用XJad对这个类进行反编译,发现XJad报错。使用了Lambda后XJad反编译工具无法反编译。我们使用JDK自带的一个工具:javap,对字节码进行反汇编,查看字节码指令。
  1. javap -c -p 文件名.class
  2. -c:表示对代码进行反编译
  3. -p:显示所有类和成员
  • 反编译的效果如下:

反编译效果.png

  • 可以看到在类中多了一个私有的静态方法lambda$main$0。这个方法里面存放的是什么内容,我们可以通过断点调试来看看:

断点调试lambda$main$0.png

  • 可以确认lambda$main$0里面放的就是Lambda中的内容,那么我们可以这么理解lambda$main$0方法:
  1. package com.sunxaiping.jdk8;
  2. public class LambdaDemo3 {
  3. public static void main(String[] args) {
  4. ...
  5. }
  6. private static void lambda$main$0(){
  7. System.out.println("Lambda的游泳");
  8. }
  9. }
  • 关于这个方法lambda$main$0的命名:以lambda开头,因为是在main函数里面使用了Lambda表达式,所以带有$main表示,因为是第一个,所以$0
  • 如果调用这个方法?其实Lambda在运行的时候会生成一个内部类,为了验证是否生成内部类,可以在运行的时候加上-Djdk.internal.lambda.dumpProxyClasses,加上这个参数后,运行时会将生成的内部class码输出到一个文件中。其命令如下:
  1. java -Djdk.internal.lambda.dumpProxyClasses 要运行的包名.类名
  • 根据上面的格式,在命令行输入以下的命令:
  1. java -Djdk.internal.lambda.dumpProxyClasses com.sunxaiping.jdk8.LambdaDemo3

验证Lambda是否生成内部类.png

  • 执行完毕,可以看到生成一个新的类,效果如下:

验证Lambda生成内部类.png

  • 反编译LambdaDemo3$$Lambda$1.class这个字节码文件,内容如下:
  1. // Decompiled by Jad v1.5.8e2. Copyright 2001 Pavel Kouznetsov.
  2. // Jad home page: http://kpdus.tripod.com/jad.html
  3. // Decompiler options: packimports(3) fieldsfirst ansi space
  4. package com.sunxaiping.jdk8;
  5. // Referenced classes of package com.sunxaiping.jdk8:
  6. // Swimmable, LambdaDemo3
  7. final class LambdaDemo3$$Lambda$1
  8. implements Swimmable
  9. {
  10. public void swimming()
  11. {
  12. LambdaDemo3.lambda$main$0();
  13. }
  14. private LambdaDemo3$$Lambda$1()
  15. {
  16. }
  17. }
  • 可以看到这个匿名内部类实现了Swimmable接口,并且重写了swimming方法,swimming方法调用LambdaDemo3.lambda$main$0(),也就是调用Lambda中的内容。最后可以将Lambda理解为:
  1. package com.sunxaiping.jdk8;
  2. public class LambdaDemo3 {
  3. public static void main(String[] args) {
  4. goSwimming(new Swimmable() {
  5. @Override
  6. public void swimming() {
  7. LambdaDemo3.lambda$main$0();
  8. }
  9. });
  10. }
  11. private static void lambda$main$0(){
  12. System.out.println("Lambda的游泳");
  13. }
  14. }

3.4 Lambda的省略格式

  • 在Lambda标准格式的基础上,使用省略写法的规则是:
  • JDK8 - 图13小括号内的参数的类型可以省略。
  • JDK8 - 图14如果小括号内有且仅有一个参数,则小括号可以省略。
  • JDK8 - 图15如果大括号内有且仅有一个语句,则可以同时省略大括号、return关键字以及语句的分号。
  • 示例:
  • Lambda标准格式:
  1. (int a ) -> {
  2. return new Person();
  3. }
  • Lambda表达式省略后:
  1. a -> new Person()

3.5 Lambda的前提条件

  • Lambda的语法非常简洁,但是Lambda表达式不是随随便便就能使用的,使用时需要注意以下几个条件:
  • JDK8 - 图16方法的参数或局部变量类型必须为接口才能使用Lambda。
  • JDK8 - 图17接口中有且仅有一个抽象方法。
  • 示例:
  1. package com.sunxaiping.jdk8;
  2. /**
  3. * 只有一个抽象方法的接口称为函数函数式接口。
  4. * @FunctionalInterface 注解用来检测这个接口是不是只有一个抽象方法
  5. */
  6. @FunctionalInterface
  7. public interface Flyable {
  8. void fly();
  9. }
  1. package com.sunxaiping.jdk8;
  2. public class LambdaCondition {
  3. public static void main(String[] args) {
  4. test(() -> {
  5. System.out.println("飞");
  6. });
  7. //局部变量类型是接口,可以使用Lambda
  8. Flyable flyable = () -> {
  9. System.out.println("飞");
  10. };
  11. }
  12. /**
  13. * 方法的参数类型,可以使用Lambda
  14. *
  15. * @param flyable
  16. */
  17. public static void test(Flyable flyable) {
  18. flyable.fly();
  19. }
  20. }

3.6 函数式接口

  • 函数式接口在Java中是指有且仅有一个抽象方法的接口。
  • 函数式接口,即适用于函数式编程场景的接口。而Java中的函数式编程体现就是Lambda,所以函数式接口就是可以适用于Lambda使用的接口。只有确保接口中有且仅有一个抽象方法,Java中的Lambda才能顺利的进行推导。
  • Java8中专门为函数式接口引入了一个新的注解:@FunctionalInterface。该注解用于接口的定义上。
  1. package com.sunxaiping.jdk8;
  2. /**
  3. * 只有一个抽象方法的接口称为函数函数式接口。
  4. * @FunctionalInterface 注解用来检测这个接口是不是只有一个抽象方法
  5. */
  6. @FunctionalInterface
  7. public interface Flyable {
  8. void fly();
  9. }
  • 一旦使用该注解来定义接口,编译器将会强制检查是否确实仅有一个抽象方法,否则将会报错。不过,即使不使用该注解,只要满足函数式接口的定义,这仍然是一个函数式接口,使用起来都一样。

3.7 Lambda和匿名内部类的对比

  • 所需的类型不一样:
    • 匿名内部类,需要的类型可以是类、抽象类、接口。
    • Lambda,需要的类型必须是接口。
  • 抽象方法数量不一样:
    • 匿名内部类所需接口中的抽象方法的数量随意。
    • Lambda所需接口中的抽象方法的数量有且仅有一个。
  • 实现原理不同:
    • 匿名内部类是在编译后会形成class文件。
    • Lambda是在程序运行的时候动态生成class文件。

3.8 JDK8接口新增的两种方法

3.8.1 概述

  • 在JDK8以前的接口:
  1. interface 接口名{
  2. 静态常量;
  3. 抽象方法;
  4. }
  • JDK8对接口进行了增强,接口还可以有默认方法和静态方法。
  1. interface 接口名{
  2. 静态常量;
  3. 抽象方法;
  4. 默认方法;
  5. 静态方法;
  6. }

3.8.2 接口引入默认方法的背景

  • 在JDK8以前接口中只能有抽象方法。存在如下问题:
  • 如果给接口中新增抽象方法,所有实现类都必须重写这个抽象方法。不利于接口的扩展。
  1. interface A{
  2. void test1();
  3. //接口新增抽象方法,所有实现类都需要去重写这个方法,非常不利于接口的扩展
  4. void test2();
  5. }
  6. interface B implements A{
  7. @Override
  8. public void test1(){
  9. System.out.println("B test1");
  10. }
  11. //接口新增抽象方法,所有实现类都需要去重写这个方法
  12. @Override
  13. public void test2(){
  14. System.out.println("B test2");
  15. }
  16. }
  • 例如,JDK8的时候,Map接口新增了forEach方法:
  1. public interface Map<K,V> {
  2. ...
  3. void forEach(BiConsumer<? super K, ? super V> action) {}
  4. }
  • 通过API可以查询到Map接口的实现类:

Map接口的实现类.png

  • 如果在Map接口中增加一个抽象方法,所有的实现类都需要去实现这个方法,那么工程量是巨大的。
  • 因此,在JDK8为接口新增了默认方法,效果如下:
  1. public interface Map<K,V> {
  2. ...
  3. default void forEach(BiConsumer<? super K, ? super V> action) {
  4. Objects.requireNonNull(action);
  5. for (Map.Entry<K, V> entry : entrySet()) {
  6. K k;
  7. V v;
  8. try {
  9. k = entry.getKey();
  10. v = entry.getValue();
  11. } catch(IllegalStateException ise) {
  12. // this usually means the entry is no longer in the map.
  13. throw new ConcurrentModificationException(ise);
  14. }
  15. action.accept(k, v);
  16. }
  17. }
  18. }
  • 接口中的默认方法实现类不必重写,可以直接使用,实现类也可以根据需要重写,这样就方便接口的扩展。

3.8.3 接口默认方法的定义格式

  1. interface 接口名{
  2. default 返回值类型 方法名(){
  3. //代码;
  4. }
  5. }

3.8.4 接口的默认方法的使用

  • JDK8 - 图19实现类可以直接使用接口的默认方法。
  1. package com.sunxaiping.jdk8;
  2. public class DefaultFunction {
  3. public static void main(String[] args) {
  4. BB bb = new BB();
  5. bb.show();
  6. }
  7. }
  8. interface AA{
  9. default void show(){
  10. System.out.println("我是AA接口中的默认方法");
  11. }
  12. }
  13. //默认方法的使用方式一:实现类可以直接使用
  14. class BB implements AA{
  15. }
  • JDK8 - 图20实现类重写接口的默认方法。
  1. package com.sunxaiping.jdk8;
  2. public class DefaultFunction {
  3. public static void main(String[] args) {
  4. BB bb = new BB();
  5. bb.show();
  6. CC cc = new CC();
  7. cc.show();
  8. }
  9. }
  10. interface AA{
  11. default void show(){
  12. System.out.println("我是AA接口中的默认方法");
  13. }
  14. }
  15. //默认方法的使用方式一:实现类可以直接使用
  16. class BB implements AA{
  17. }
  18. //默认方法的使用方式二:实现类可以重写默认方法
  19. class CC implements AA{
  20. @Override
  21. public void show() {
  22. System.out.println("我是CC类重写的默认方法");
  23. }
  24. }

3.8.5 接口静态方法的定义格式

  1. interface 接口名{
  2. static 返回值类型 方法名(){
  3. //代码
  4. }
  5. }

3.8.6 接口静态方法的使用

  • 直接使用接口名调用即可:接口名.静态方法名();
  • 常用接口中的静态方法不能被继承,也不能被重写。
  1. package com.sunxaiping.jdk8;
  2. public class DefaultFunction {
  3. public static void main(String[] args) {
  4. AA.show();
  5. }
  6. }
  7. interface AA{
  8. static void show(){
  9. System.out.println("我是接口的静态方法");
  10. }
  11. }

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

  • JDK8 - 图21接口中的默认方法是通过实例调用,而接口中的静态方法是通过接口名调用。
  • JDK8 - 图22接口中的默认方法可以被继承,实现类可以直接使用接口中的默认方法,也可以重写接口中的默认方法。
  • JDK8 - 图23接口中的静态方法不能被继承,实现类也不能重写接口中的静态方法,只能使用接口名调用。

3.9 常用内置函数式接口

3.9.1 内置函数式接口的由来

  • 我们知道使用Lambda表达式的前提是需要有函数式接口。而Lambda使用时不关心接口名、抽象方法名,只关系抽象方法的参数列表和返回值类型。因此为了让我们使用Lambda方便,JDK提供了大量常用的函数式接口。
  1. package com.sunxaiping.jdk8;
  2. public class LambdaDemo5 {
  3. public static void main(String[] args) {
  4. test((a1, a2) -> {
  5. System.out.println(a1 + a2);
  6. });
  7. }
  8. public static void test(Operation operation) {
  9. operation.getSum(1, 2);
  10. }
  11. }
  12. interface Operation {
  13. void getSum(int a, int b);
  14. }

3.9.2 常用的函数式接口介绍

  • 它们主要在java.util.function包中。下面是最常用的几个接口:
  • JDK8 - 图24Supplier接口:供给型接口
  1. @FunctionalInterface
  2. public interface Supplier<T> {
  3. /**
  4. * Gets a result.
  5. *
  6. * @return a result
  7. */
  8. T get();
  9. }
  • JDK8 - 图25Consumer接口:消费型接口。
  1. @FunctionalInterface
  2. public interface Consumer<T> {
  3. /**
  4. * Performs this operation on the given argument.
  5. *
  6. * @param t the input argument
  7. */
  8. void accept(T t);
  9. /**
  10. * Returns a composed {@code Consumer} that performs, in sequence, this
  11. * operation followed by the {@code after} operation. If performing either
  12. * operation throws an exception, it is relayed to the caller of the
  13. * composed operation. If performing this operation throws an exception,
  14. * the {@code after} operation will not be performed.
  15. *
  16. * @param after the operation to perform after this operation
  17. * @return a composed {@code Consumer} that performs in sequence this
  18. * operation followed by the {@code after} operation
  19. * @throws NullPointerException if {@code after} is null
  20. */
  21. default Consumer<T> andThen(Consumer<? super T> after) {
  22. Objects.requireNonNull(after);
  23. return (T t) -> { accept(t); after.accept(t); };
  24. }
  25. }
  • JDK8 - 图26Function:函数型接口。
  1. @FunctionalInterface
  2. public interface Function<T, R> {
  3. /**
  4. * Applies this function to the given argument.
  5. *
  6. * @param t the function argument
  7. * @return the function result
  8. */
  9. R apply(T t);
  10. /**
  11. * Returns a composed function that first applies the {@code before}
  12. * function to its input, and then applies this function to the result.
  13. * If evaluation of either function throws an exception, it is relayed to
  14. * the caller of the composed function.
  15. *
  16. * @param <V> the type of input to the {@code before} function, and to the
  17. * composed function
  18. * @param before the function to apply before this function is applied
  19. * @return a composed function that first applies the {@code before}
  20. * function and then applies this function
  21. * @throws NullPointerException if before is null
  22. *
  23. * @see #andThen(Function)
  24. */
  25. default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
  26. Objects.requireNonNull(before);
  27. return (V v) -> apply(before.apply(v));
  28. }
  29. /**
  30. * Returns a composed function that first applies this function to
  31. * its input, and then applies the {@code after} function to the result.
  32. * If evaluation of either function throws an exception, it is relayed to
  33. * the caller of the composed function.
  34. *
  35. * @param <V> the type of output of the {@code after} function, and of the
  36. * composed function
  37. * @param after the function to apply after this function is applied
  38. * @return a composed function that first applies this function and then
  39. * applies the {@code after} function
  40. * @throws NullPointerException if after is null
  41. *
  42. * @see #compose(Function)
  43. */
  44. default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
  45. Objects.requireNonNull(after);
  46. return (T t) -> after.apply(apply(t));
  47. }
  48. /**
  49. * Returns a function that always returns its input argument.
  50. *
  51. * @param <T> the type of the input and output objects to the function
  52. * @return a function that always returns its input argument
  53. */
  54. static <T> Function<T, T> identity() {
  55. return t -> t;
  56. }
  57. }
  • JDK8 - 图27Predicate:断言型接口。
  1. @FunctionalInterface
  2. public interface Predicate<T> {
  3. /**
  4. * Evaluates this predicate on the given argument.
  5. *
  6. * @param t the input argument
  7. * @return {@code true} if the input argument matches the predicate,
  8. * otherwise {@code false}
  9. */
  10. boolean test(T t);
  11. /**
  12. * Returns a composed predicate that represents a short-circuiting logical
  13. * AND of this predicate and another. When evaluating the composed
  14. * predicate, if this predicate is {@code false}, then the {@code other}
  15. * predicate is not evaluated.
  16. *
  17. * <p>Any exceptions thrown during evaluation of either predicate are relayed
  18. * to the caller; if evaluation of this predicate throws an exception, the
  19. * {@code other} predicate will not be evaluated.
  20. *
  21. * @param other a predicate that will be logically-ANDed with this
  22. * predicate
  23. * @return a composed predicate that represents the short-circuiting logical
  24. * AND of this predicate and the {@code other} predicate
  25. * @throws NullPointerException if other is null
  26. */
  27. default Predicate<T> and(Predicate<? super T> other) {
  28. Objects.requireNonNull(other);
  29. return (t) -> test(t) && other.test(t);
  30. }
  31. /**
  32. * Returns a predicate that represents the logical negation of this
  33. * predicate.
  34. *
  35. * @return a predicate that represents the logical negation of this
  36. * predicate
  37. */
  38. default Predicate<T> negate() {
  39. return (t) -> !test(t);
  40. }
  41. /**
  42. * Returns a composed predicate that represents a short-circuiting logical
  43. * OR of this predicate and another. When evaluating the composed
  44. * predicate, if this predicate is {@code true}, then the {@code other}
  45. * predicate is not evaluated.
  46. *
  47. * <p>Any exceptions thrown during evaluation of either predicate are relayed
  48. * to the caller; if evaluation of this predicate throws an exception, the
  49. * {@code other} predicate will not be evaluated.
  50. *
  51. * @param other a predicate that will be logically-ORed with this
  52. * predicate
  53. * @return a composed predicate that represents the short-circuiting logical
  54. * OR of this predicate and the {@code other} predicate
  55. * @throws NullPointerException if other is null
  56. */
  57. default Predicate<T> or(Predicate<? super T> other) {
  58. Objects.requireNonNull(other);
  59. return (t) -> test(t) || other.test(t);
  60. }
  61. /**
  62. * Returns a predicate that tests if two arguments are equal according
  63. * to {@link Objects#equals(Object, Object)}.
  64. *
  65. * @param <T> the type of arguments to the predicate
  66. * @param targetRef the object reference with which to compare for equality,
  67. * which may be {@code null}
  68. * @return a predicate that tests if two arguments are equal according
  69. * to {@link Objects#equals(Object, Object)}
  70. */
  71. static <T> Predicate<T> isEqual(Object targetRef) {
  72. return (null == targetRef)
  73. ? Objects::isNull
  74. : object -> targetRef.equals(object);
  75. }
  76. }

3.9.3 Supplier接口

  • java.util.function.Supplier<T>接口,它意味着“供给”,对应的Lambda表达式需要对外提供一个符合泛型类型的对象数据。
  1. @FunctionalInterface
  2. public interface Supplier<T> {
  3. /**
  4. * Gets a result.
  5. *
  6. * @return a result
  7. */
  8. T get();
  9. }
  • 供给型接口,通过Supplier接口中的get方法可以得到一个值,无参有返回值的接口。
  • 示例:使用Lambda表达式返回数组元素的最大值。
  1. package com.sunxaiping.jdk8;
  2. import java.util.Arrays;
  3. import java.util.function.Supplier;
  4. public class LambdaDemo6 {
  5. public static void main(String[] args) {
  6. printMax(() -> {
  7. int[] arr = {11, 99, 100, -7};
  8. Arrays.sort(arr);
  9. return arr[arr.length-1];
  10. });
  11. }
  12. public static void printMax(Supplier<Integer> supplier) {
  13. Integer max = supplier.get();
  14. System.out.println("max = " + max);
  15. }
  16. }

3.9.4 Consumer接口

  • java.util.function.Consumer<T>接口正好相反,它不是生产一个数据,而是消费一个数据,其数据类型由泛型参数决定。
  1. @FunctionalInterface
  2. public interface Consumer<T> {
  3. /**
  4. * Performs this operation on the given argument.
  5. *
  6. * @param t the input argument
  7. */
  8. void accept(T t);
  9. /**
  10. * Returns a composed {@code Consumer} that performs, in sequence, this
  11. * operation followed by the {@code after} operation. If performing either
  12. * operation throws an exception, it is relayed to the caller of the
  13. * composed operation. If performing this operation throws an exception,
  14. * the {@code after} operation will not be performed.
  15. *
  16. * @param after the operation to perform after this operation
  17. * @return a composed {@code Consumer} that performs in sequence this
  18. * operation followed by the {@code after} operation
  19. * @throws NullPointerException if {@code after} is null
  20. */
  21. default Consumer<T> andThen(Consumer<? super T> after) {
  22. Objects.requireNonNull(after);
  23. return (T t) -> { accept(t); after.accept(t); };
  24. }
  25. }
  • 示例:使用Lambda表达式将一个字符串转成大写和小写字符串。
  1. package com.sunxaiping.jdk8;
  2. import java.util.function.Consumer;
  3. public class LambdaDemo7 {
  4. public static void main(String[] args) {
  5. test((s)->{
  6. String lowerCase = s.toLowerCase();
  7. System.out.println(lowerCase);
  8. String upperCase = s.toUpperCase();
  9. System.out.println(upperCase);
  10. });
  11. }
  12. public static void test(Consumer<String> consumer){
  13. consumer.accept("hello world");
  14. }
  15. }
  • 示例:使用Lambda表达式将一个字符串先转成小写然后在转成大写。
  1. package com.sunxaiping.jdk8;
  2. import java.util.function.Consumer;
  3. public class LambdaDemo8 {
  4. public static void main(String[] args) {
  5. //使用Lambda表达式先将一个字符串转成小写,再转成大写
  6. test((s) -> {
  7. System.out.println(s.toLowerCase());
  8. }, (s) -> {
  9. System.out.println(s.toUpperCase());
  10. });
  11. }
  12. public static void test(Consumer<String> c1, Consumer<String> c2) {
  13. c1.andThen(c2).accept("hello world");
  14. }
  15. }

3.9.5 Function接口

  • java.util.function.Function<T, R>接口用来根据一个类型的数据得到另一个类型的数据,前者称为前置条件,后者称为后置条件。有参数有返回值。
  1. @FunctionalInterface
  2. public interface Function<T, R> {
  3. /**
  4. * Applies this function to the given argument.
  5. *
  6. * @param t the function argument
  7. * @return the function result
  8. */
  9. R apply(T t);
  10. /**
  11. * Returns a composed function that first applies the {@code before}
  12. * function to its input, and then applies this function to the result.
  13. * If evaluation of either function throws an exception, it is relayed to
  14. * the caller of the composed function.
  15. *
  16. * @param <V> the type of input to the {@code before} function, and to the
  17. * composed function
  18. * @param before the function to apply before this function is applied
  19. * @return a composed function that first applies the {@code before}
  20. * function and then applies this function
  21. * @throws NullPointerException if before is null
  22. *
  23. * @see #andThen(Function)
  24. */
  25. default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
  26. Objects.requireNonNull(before);
  27. return (V v) -> apply(before.apply(v));
  28. }
  29. /**
  30. * Returns a composed function that first applies this function to
  31. * its input, and then applies the {@code after} function to the result.
  32. * If evaluation of either function throws an exception, it is relayed to
  33. * the caller of the composed function.
  34. *
  35. * @param <V> the type of output of the {@code after} function, and of the
  36. * composed function
  37. * @param after the function to apply after this function is applied
  38. * @return a composed function that first applies this function and then
  39. * applies the {@code after} function
  40. * @throws NullPointerException if after is null
  41. *
  42. * @see #compose(Function)
  43. */
  44. default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
  45. Objects.requireNonNull(after);
  46. return (T t) -> after.apply(apply(t));
  47. }
  48. /**
  49. * Returns a function that always returns its input argument.
  50. *
  51. * @param <T> the type of the input and output objects to the function
  52. * @return a function that always returns its input argument
  53. */
  54. static <T> Function<T, T> identity() {
  55. return t -> t;
  56. }
  57. }
  • 示例:
  1. package com.sunxiaping.jdk8;
  2. import java.util.function.Function;
  3. public class LambdaDemo1 {
  4. //使用Lambda表达式将字符串转成数字
  5. public static void main(String[] args) {
  6. getNumber((s) -> {
  7. int num = Integer.parseInt(s);
  8. return num;
  9. });
  10. }
  11. public static void getNumber(Function<String, Integer> function) {
  12. Integer num = function.apply("10");
  13. System.out.println("num = " + num);
  14. }
  15. }

3.9.6 Predicate接口

  • 有时我们需要对某种类型的数据进行判断,从而得到一个boolean值的结果,这时可以使用java.util.function.Predicate<T>接口。
  1. @FunctionalInterface
  2. public interface Predicate<T> {
  3. /**
  4. * Evaluates this predicate on the given argument.
  5. *
  6. * @param t the input argument
  7. * @return {@code true} if the input argument matches the predicate,
  8. * otherwise {@code false}
  9. */
  10. boolean test(T t);
  11. /**
  12. * Returns a composed predicate that represents a short-circuiting logical
  13. * AND of this predicate and another. When evaluating the composed
  14. * predicate, if this predicate is {@code false}, then the {@code other}
  15. * predicate is not evaluated.
  16. *
  17. * <p>Any exceptions thrown during evaluation of either predicate are relayed
  18. * to the caller; if evaluation of this predicate throws an exception, the
  19. * {@code other} predicate will not be evaluated.
  20. *
  21. * @param other a predicate that will be logically-ANDed with this
  22. * predicate
  23. * @return a composed predicate that represents the short-circuiting logical
  24. * AND of this predicate and the {@code other} predicate
  25. * @throws NullPointerException if other is null
  26. */
  27. default Predicate<T> and(Predicate<? super T> other) {
  28. Objects.requireNonNull(other);
  29. return (t) -> test(t) && other.test(t);
  30. }
  31. /**
  32. * Returns a predicate that represents the logical negation of this
  33. * predicate.
  34. *
  35. * @return a predicate that represents the logical negation of this
  36. * predicate
  37. */
  38. default Predicate<T> negate() {
  39. return (t) -> !test(t);
  40. }
  41. /**
  42. * Returns a composed predicate that represents a short-circuiting logical
  43. * OR of this predicate and another. When evaluating the composed
  44. * predicate, if this predicate is {@code true}, then the {@code other}
  45. * predicate is not evaluated.
  46. *
  47. * <p>Any exceptions thrown during evaluation of either predicate are relayed
  48. * to the caller; if evaluation of this predicate throws an exception, the
  49. * {@code other} predicate will not be evaluated.
  50. *
  51. * @param other a predicate that will be logically-ORed with this
  52. * predicate
  53. * @return a composed predicate that represents the short-circuiting logical
  54. * OR of this predicate and the {@code other} predicate
  55. * @throws NullPointerException if other is null
  56. */
  57. default Predicate<T> or(Predicate<? super T> other) {
  58. Objects.requireNonNull(other);
  59. return (t) -> test(t) || other.test(t);
  60. }
  61. /**
  62. * Returns a predicate that tests if two arguments are equal according
  63. * to {@link Objects#equals(Object, Object)}.
  64. *
  65. * @param <T> the type of arguments to the predicate
  66. * @param targetRef the object reference with which to compare for equality,
  67. * which may be {@code null}
  68. * @return a predicate that tests if two arguments are equal according
  69. * to {@link Objects#equals(Object, Object)}
  70. */
  71. static <T> Predicate<T> isEqual(Object targetRef) {
  72. return (null == targetRef)
  73. ? Objects::isNull
  74. : object -> targetRef.equals(object);
  75. }
  76. }
  • 示例:使用Lambda判断一个名称,如果名称超过3个字就认为是很长的名称。
  1. package com.sunxiaping.jdk8;
  2. import java.util.function.Predicate;
  3. public class LambdaDemo2 {
  4. //使用Lambda判断一个名称,如果名称超过3个字就认为是很长的名称
  5. public static void main(String[] args) {
  6. test((name) -> {
  7. return name.length() > 3;
  8. }, "迪丽热巴");
  9. }
  10. public static void test(Predicate<String> predicate, String name) {
  11. boolean test = predicate.test(name);
  12. if (test) {
  13. System.out.println(name + "的名称很长");
  14. } else {
  15. System.out.println(name + "的名称不长");
  16. }
  17. }
  18. }
  • 示例:
  1. package com.sunxiaping.jdk8;
  2. import java.util.function.Predicate;
  3. public class LambdaDemo3 {
  4. public static void main(String[] args) {
  5. //使用Lambda表达式判断一个字符串即包含W也包含H
  6. testAnd(s1 -> s1.contains("W"), s2 -> s2.contains("H"), "Hello World");
  7. //使用Lambda表达式判断一个字符串包含W或包含H
  8. testOr(s1 -> s1.contains("W"), s2 -> s2.contains("H"), "Hello World");
  9. //使用Lambda表达式判断一个字符串不包含W
  10. testNegate(s1 -> s1.contains("W"), "Hello world");
  11. }
  12. public static void testAnd(Predicate<String> p1, Predicate<String> p2, String str) {
  13. boolean test = p1.and(p2).test(str);
  14. if (test) {
  15. System.out.println(str + "既包含W也包含H");
  16. }
  17. }
  18. public static void testOr(Predicate<String> p1, Predicate<String> p2, String str) {
  19. boolean test = p1.or(p2).test(str);
  20. if (test) {
  21. System.out.println(str + "包含W或包含H");
  22. }
  23. }
  24. public static void testNegate(Predicate<String> p1, String str) {
  25. boolean test = p1.negate().test(str);
  26. if (test) {
  27. System.out.println(str + "不包含W");
  28. }
  29. }
  30. }

3.10 方法引用

3.10.1 介绍方法引用

  • 示例:使用Lambda表达式求一个数组的和
  1. package com.sunxiaping.jdk8;
  2. import java.util.function.Consumer;
  3. public class LambdaDemo4 {
  4. /**
  5. * 获取一个数组的和
  6. *
  7. * @param arr
  8. */
  9. public static void getSum(int[] arr) {
  10. int sum = 0;
  11. for (int i : arr) {
  12. sum += i;
  13. }
  14. System.out.println("sum = " + sum);
  15. }
  16. public static void main(String[] args) {
  17. int[] arrs = {10, 19, -10, 0};
  18. //使用方法引用:让这个指定的方法去重写接口的抽象方法,到时候调用接口的抽象方法就是调用传递过去的这个方法
  19. printSum(LambdaDemo4::getSum,arrs);
  20. Consumer<int[]> consumer = LambdaDemo4::getSum;
  21. consumer.accept(arrs);
  22. }
  23. public static void printSum(Consumer<int[]> consumer, int[] arr) {
  24. consumer.accept(arr);
  25. }
  26. }
  • 注意其中的双冒号::写法,这被称为”方法引用”,是一种新的语法。

方法引用的前提:

  • JDK8 - 图28方法引用所引用的方法的参数列表必须要和函数式接口中抽象方法的参数列表相同(完全一致)。
  • JDK8 - 图29方法引用所引用的方法的的返回值类型必须要和函数式接口中抽象方法的返回值类型相同(完全一致)。

3.10.2 方法引用的格式

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

3.10.3 常用的引用方式

  • 方法引用在JDK8中使用方式非常灵活,有以下几种形式。
  • JDK8 - 图30实例名::成员方法名。
  • JDK8 - 图31类名::静态方法名。
  • JDK8 - 图32类名::方法名。
  • JDK8 - 图33类名::new。
  • JDK8 - 图34数据类型[]::new。

3.10.4 实例名::成员方法名

  • 如果一个类中已经存在了一个成员方法,则可以通过实例名引用成员方法。
  1. package com.sunxiaping.jdk8;
  2. import java.util.Date;
  3. import java.util.function.Supplier;
  4. /**
  5. * 方法引用: 实例名::方法名
  6. */
  7. public class LambdaDemo5 {
  8. public static void main(String[] args) {
  9. //使用Lambda表达式获取当前秒数
  10. Date date = new Date();
  11. Supplier<Long> supplier = () -> {
  12. return date.getTime();
  13. };
  14. System.out.println(supplier.get());
  15. //使用方法引用简化上述代码
  16. supplier = date::getTime;
  17. System.out.println(supplier.get());
  18. }
  19. }

3.10.5 类名::静态方法名

  • 由于在java.lang.System类中已经存在了许多静态方法,比如currentTimeMillis()方法,所以当我们需要通过Lambda来调用这些静态方法的时候,可以使用类名::静态方法名。
  1. package com.sunxiaping.jdk8;
  2. import java.util.function.Supplier;
  3. /**
  4. * 方法引用: 类名::静态方法名
  5. */
  6. public class LambdaDemo6 {
  7. public static void main(String[] args) {
  8. //使用Lambda表达式获取当前的毫秒值
  9. Supplier<Long> supplier = ()->{
  10. return System.currentTimeMillis();
  11. };
  12. System.out.println("supplier = " + supplier.get());
  13. //使用方法引用简化上面的代码
  14. supplier = System::currentTimeMillis;
  15. System.out.println("supplier = " + supplier.get());
  16. }
  17. }

3.10.6 类名::方法名

  • Java面向对象中,类名只能调用静态方法,类名引用实例方法是有前提的,实际上是拿第一个参数作为方法的调用者。
  1. package com.sunxiaping.jdk8;
  2. import java.util.function.Function;
  3. /**
  4. * 方法引用 类名::方法名
  5. */
  6. public class LambdaDemo7 {
  7. public static void main(String[] args) {
  8. //使用Lambda表达式将字符串转换为Long类型
  9. Function<String, Long> function = (s) -> {
  10. return Long.parseLong(s);
  11. };
  12. Long apply = function.apply("5");
  13. System.out.println("apply = " + apply);
  14. //使用Lambda简化上面的代码
  15. function = Long::parseLong;
  16. apply = function.apply("5");
  17. System.out.println("apply = " + apply);
  18. }
  19. }

3.10.7 类名::new

  • 由于构造器的名称和类名完全一样,所以构造器引用使用类名::new的格式表示。
  1. package com.sunxiaping.jdk8;
  2. import java.util.function.BiFunction;
  3. import java.util.function.Supplier;
  4. /**
  5. * 方法引用 类名::new
  6. */
  7. public class LambdaDemo8 {
  8. public static void main(String[] args) {
  9. //使用Lambda表达式获取Person类对象
  10. Supplier<Person> supplier = () -> {
  11. return new Person();
  12. };
  13. Person person = supplier.get();
  14. System.out.println("person = " + person);
  15. supplier = Person::new;
  16. person = supplier.get();
  17. System.out.println("person = " + person);
  18. BiFunction<String, Integer, Person> function = (name, age) -> {
  19. return new Person(name, age);
  20. };
  21. person = function.apply("李四", 20);
  22. System.out.println("person = " + person);
  23. function = Person::new;
  24. person = function.apply("张三", 25);
  25. System.out.println("person = " + person);
  26. }
  27. }

3.10 数据类型[]::new

  • 数组也是Object的子类,所以具有同样的构造器。
  1. package com.sunxiaping.jdk8;
  2. import java.util.function.Function;
  3. /**
  4. * 方法引用 数据类型[]::new
  5. */
  6. public class LambdaDemo9 {
  7. public static void main(String[] args) {
  8. //使用Lambda表达式创建指定长度的String数组
  9. Function<Integer, String[]> function = (length) -> {
  10. return new String[length];
  11. };
  12. String[] str = function.apply(2);
  13. System.out.println("str.length = " + str.length);
  14. //使用方法引用简化上面的代码
  15. function = String[]::new;
  16. str = function.apply(5);
  17. System.out.println("str.length = " + str.length);
  18. }
  19. }

3.10.11 总结

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

3.11 Stream API

3.11.1 集合处理数据的弊端

  • 当我们需要对集合中的元素进行操作的时候,除了必需的添加、删除、获取外,最典型的就是集合的遍历。我们来体验集合操作数据的弊端,需求如下:
  1. 一个ArrayList集合中存储有以下数据:张无忌、周芷若、赵敏、张强、张三丰
  2. 需求:①拿到所有姓张的 ②拿到名字长度为3个字的 ③打印这些数据
  • 代码如下:
  1. package com.sunxiaping.jdk8;
  2. import java.util.ArrayList;
  3. import java.util.Collections;
  4. import java.util.List;
  5. public class StreamIntroDemo {
  6. public static void main(String[] args) {
  7. List<String> list = new ArrayList<>();
  8. Collections.addAll(list, "张无忌", "周芷若", "赵敏", "张强", "张三丰");
  9. //拿到所有姓张的
  10. List<String> zhangList = new ArrayList<>();
  11. for (String s : list) {
  12. if (s.startsWith("张")) {
  13. zhangList.add(s);
  14. }
  15. }
  16. //拿到名字长度=3的
  17. List<String> threeList = new ArrayList<>();
  18. for (String s : zhangList) {
  19. if (s.length() == 3) {
  20. threeList.add(s);
  21. }
  22. }
  23. //对结果进行打印
  24. for (String name : threeList) {
  25. System.out.println(name);
  26. }
  27. }
  28. }
  • 循环遍历的弊端:
    • 上面的代码中包含三个循环,每一个作用不同:
      • JDK8 - 图35首先筛选所有姓张的人。
      • JDK8 - 图36然后筛选名字中有三个字的人。
      • JDK8 - 图37最后对结果进行打印输出。
      • 每当我们需要对集合中的元素进行操作的时候,总是需要进行循环、循环、再循环,这样太麻烦了。
  • Stream的优雅的写法:
  1. package com.sunxiaping.jdk8;
  2. import java.util.ArrayList;
  3. import java.util.Collections;
  4. import java.util.List;
  5. public class LambdaDemo10 {
  6. public static void main(String[] args) {
  7. List<String> list = new ArrayList<>();
  8. Collections.addAll(list, "张无忌", "周芷若", "赵敏", "张强", "张三丰");
  9. list.stream().filter(name->name.startsWith("张")).filter((name)->name.length()==3).forEach(System.out::println);
  10. }
  11. }

3.11.2 Stream流式思想概述

  • Stream流式思想类似于工厂车间的”生产流水线”,Stream流不是一种数据结构,不保存数据,而是对数据进行加工处理。Stream可以看作是流水线上的一个工序。在流水线上,通过多个工序让一个原材料加工成一个商品。

Stream流式思想1.png

Stream流式思想2.png

  • Stream API能让我们快速完成许多重复的操作,如筛选,切片、映射、查找、去除重复、统计、匹配和归约。

3.11.3 获取Stream流的方式

  • JDK8 - 图40java.util.Collection接口中加入了default方法stream()用来获取流,所以其所有的实现类均可获取Stream流。
  1. public interface Collection<E> extends Iterable<E> {
  2. default Stream<E> stream() {
  3. return StreamSupport.stream(spliterator(), false);
  4. }
  5. //略
  6. }
  1. package com.sunxiaping.jdk8;
  2. import java.util.Arrays;
  3. import java.util.List;
  4. /**
  5. * 获取Stream流的方式
  6. */
  7. public class LambdaDemo11 {
  8. public static void main(String[] args) {
  9. List<Integer> list = Arrays.asList(1, 2, 3);
  10. list.stream().forEach(System.out::println);
  11. }
  12. }
  • JDK8 - 图41Stream接口的静态方法of可以获取数组对应的Stream流。
  1. public interface Stream<T> extends BaseStream<T, Stream<T>> {
  2. /**
  3. * Returns a sequential {@code Stream} containing a single element.
  4. *
  5. * @param t the single element
  6. * @param <T> the type of stream elements
  7. * @return a singleton sequential stream
  8. */
  9. public static<T> Stream<T> of(T t) {
  10. return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);
  11. }
  12. /**
  13. * Returns a sequential ordered stream whose elements are the specified values.
  14. *
  15. * @param <T> the type of stream elements
  16. * @param values the elements of the new stream
  17. * @return the new stream
  18. */
  19. @SafeVarargs
  20. @SuppressWarnings("varargs") // Creating a stream from an array is safe
  21. public static<T> Stream<T> of(T... values) {
  22. return Arrays.stream(values);
  23. }
  24. //略
  25. }
  1. package com.sunxiaping.jdk8;
  2. import java.util.stream.Stream;
  3. /**
  4. * 获取Stream流的方式
  5. */
  6. public class LambdaDemo11 {
  7. public static void main(String[] args) {
  8. Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
  9. stream.forEach(System.out::println);
  10. }
  11. }
  • JDK8 - 图42java.util.Arrays的stream()方法获取数组对应的Stream流。
  1. public class Arrays {
  2. public static <T> Stream<T> stream(T[] array) {
  3. return stream(array, 0, array.length);
  4. }
  5. /**
  6. * Returns a sequential {@link Stream} with the specified range of the
  7. * specified array as its source.
  8. *
  9. * @param <T> the type of the array elements
  10. * @param array the array, assumed to be unmodified during use
  11. * @param startInclusive the first index to cover, inclusive
  12. * @param endExclusive index immediately past the last index to cover
  13. * @return a {@code Stream} for the array range
  14. * @throws ArrayIndexOutOfBoundsException if {@code startInclusive} is
  15. * negative, {@code endExclusive} is less than
  16. * {@code startInclusive}, or {@code endExclusive} is greater than
  17. * the array size
  18. * @since 1.8
  19. */
  20. public static <T> Stream<T> stream(T[] array, int startInclusive, int endExclusive) {
  21. return StreamSupport.stream(spliterator(array, startInclusive, endExclusive), false);
  22. }
  23. /**
  24. * Returns a sequential {@link IntStream} with the specified array as its
  25. * source.
  26. *
  27. * @param array the array, assumed to be unmodified during use
  28. * @return an {@code IntStream} for the array
  29. * @since 1.8
  30. */
  31. public static IntStream stream(int[] array) {
  32. return stream(array, 0, array.length);
  33. }
  34. /**
  35. * Returns a sequential {@link IntStream} with the specified range of the
  36. * specified array as its source.
  37. *
  38. * @param array the array, assumed to be unmodified during use
  39. * @param startInclusive the first index to cover, inclusive
  40. * @param endExclusive index immediately past the last index to cover
  41. * @return an {@code IntStream} for the array range
  42. * @throws ArrayIndexOutOfBoundsException if {@code startInclusive} is
  43. * negative, {@code endExclusive} is less than
  44. * {@code startInclusive}, or {@code endExclusive} is greater than
  45. * the array size
  46. * @since 1.8
  47. */
  48. public static IntStream stream(int[] array, int startInclusive, int endExclusive) {
  49. return StreamSupport.intStream(spliterator(array, startInclusive, endExclusive), false);
  50. }
  51. /**
  52. * Returns a sequential {@link LongStream} with the specified array as its
  53. * source.
  54. *
  55. * @param array the array, assumed to be unmodified during use
  56. * @return a {@code LongStream} for the array
  57. * @since 1.8
  58. */
  59. public static LongStream stream(long[] array) {
  60. return stream(array, 0, array.length);
  61. }
  62. /**
  63. * Returns a sequential {@link LongStream} with the specified range of the
  64. * specified array as its source.
  65. *
  66. * @param array the array, assumed to be unmodified during use
  67. * @param startInclusive the first index to cover, inclusive
  68. * @param endExclusive index immediately past the last index to cover
  69. * @return a {@code LongStream} for the array range
  70. * @throws ArrayIndexOutOfBoundsException if {@code startInclusive} is
  71. * negative, {@code endExclusive} is less than
  72. * {@code startInclusive}, or {@code endExclusive} is greater than
  73. * the array size
  74. * @since 1.8
  75. */
  76. public static LongStream stream(long[] array, int startInclusive, int endExclusive) {
  77. return StreamSupport.longStream(spliterator(array, startInclusive, endExclusive), false);
  78. }
  79. /**
  80. * Returns a sequential {@link DoubleStream} with the specified array as its
  81. * source.
  82. *
  83. * @param array the array, assumed to be unmodified during use
  84. * @return a {@code DoubleStream} for the array
  85. * @since 1.8
  86. */
  87. public static DoubleStream stream(double[] array) {
  88. return stream(array, 0, array.length);
  89. }
  90. /**
  91. * Returns a sequential {@link DoubleStream} with the specified range of the
  92. * specified array as its source.
  93. *
  94. * @param array the array, assumed to be unmodified during use
  95. * @param startInclusive the first index to cover, inclusive
  96. * @param endExclusive index immediately past the last index to cover
  97. * @return a {@code DoubleStream} for the array range
  98. * @throws ArrayIndexOutOfBoundsException if {@code startInclusive} is
  99. * negative, {@code endExclusive} is less than
  100. * {@code startInclusive}, or {@code endExclusive} is greater than
  101. * the array size
  102. * @since 1.8
  103. */
  104. public static DoubleStream stream(double[] array, int startInclusive, int endExclusive) {
  105. return StreamSupport.doubleStream(spliterator(array, startInclusive, endExclusive), false);
  106. }
  107. //略
  108. }
  1. package com.sunxiaping.jdk8;
  2. import java.util.Arrays;
  3. import java.util.stream.Stream;
  4. /**
  5. * 获取Stream流的方式
  6. */
  7. public class LambdaDemo11 {
  8. public static void main(String[] args) {
  9. Stream<Integer> stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5});
  10. stream.forEach(System.out::println);
  11. }
  12. }

3.11.4 Stream常用方法

  • Stream流模型的操作非常丰富,这里介绍一些常用的API。 | 方法名 | 方法作用 | 返回值类型 | 方法种类 | | —- | —- | —- | —- | | count | 统计个数 | long | 终结 | | forEach | 逐一处理 | void | 终结 | | filter | 过滤 | Stream | 函数拼接 | | limit | 取前几个 | Stream | 函数拼接 | | skip | 跳过前几个 | Stream | 函数拼接 | | map | 映射 | Stream | 函数拼接 | | concat | 组合 | Stream | 函数拼接 |
  • 终结方法:返回值类型不是Stream类型的方法,不再支持链式调用。
  • 非终结方法:返回值类型是Stream类型的方式,支持链式调用。

3.11.5 Stream注意事项

  • JDK8 - 图43Stream只能操作一次。
  • JDK8 - 图44Stream方法返回的是新的流。
  • JDK8 - 图45Stream不调用终结方法,中间的操作不会执行。

3.11.6 Stream流的forEach方法

  • Stream中的forEach方法用来遍历流中的数据,该方法接收一个Consumer接口函数,会将每一个流元素交给该函数进行处理
  1. public interface Stream<T> extends BaseStream<T, Stream<T>> {
  2. void forEach(Consumer<? super T> action);
  3. //略
  4. }
  • Map中的forEach方法用来遍历Map中的每个Map.Entry类型的元素,该方法接受一个BiConsumer接口函数,会将Map.Entry类型元素的key和value交给该函数进行处理。
  1. public interface Map<K,V> {
  2. default void forEach(BiConsumer<? super K, ? super V> action) {
  3. Objects.requireNonNull(action);
  4. for (Map.Entry<K, V> entry : entrySet()) {
  5. K k;
  6. V v;
  7. try {
  8. k = entry.getKey();
  9. v = entry.getValue();
  10. } catch(IllegalStateException ise) {
  11. // this usually means the entry is no longer in the map.
  12. throw new ConcurrentModificationException(ise);
  13. }
  14. action.accept(k, v);
  15. }
  16. }
  17. //略
  18. }
  • 示例:
  1. package com.sunxiaping.jdk8;
  2. import java.util.ArrayList;
  3. import java.util.Collections;
  4. import java.util.List;
  5. /**
  6. * forEach
  7. */
  8. public class LambdaDemo11 {
  9. public static void main(String[] args) {
  10. List<String> list = new ArrayList<>();
  11. Collections.addAll(list, "张三", "李四", "王五");
  12. list.stream().forEach(System.out::println);
  13. }
  14. }
  • 示例:
  1. package com.sunxiaping.jdk8;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. /**
  5. * forEach
  6. */
  7. public class LambdaDemo11 {
  8. public static void main(String[] args) {
  9. Map<String,Object> map = new HashMap<>();
  10. map.put("aa","aaa");
  11. map.put("bb","bbb");
  12. map.forEach((k,v)->{
  13. System.out.println("k = " + k);
  14. System.out.println("v = " + v);
  15. });
  16. }
  17. }

3.11.7 Stream流的count方法

  • Stream流提供count方法来统计其中的元素个数:
  1. public interface Stream<T> extends BaseStream<T, Stream<T>> {
  2. long count();
  3. //略
  4. }
  • 示例:
  1. package com.sunxiaping.jdk8;
  2. import java.util.stream.Stream;
  3. /**
  4. * count
  5. */
  6. public class LambdaDemo11 {
  7. public static void main(String[] args) {
  8. Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 0);
  9. long count = stream.count();
  10. System.out.println("count = " + count);
  11. }
  12. }

3.11.8 Stream流的filter方法

  • Stream流中的filter方法用于过滤数据,返回符合条件的数据。
  1. public interface Stream<T> extends BaseStream<T, Stream<T>> {
  2. Stream<T> filter(Predicate<? super T> predicate);
  3. //略
  4. }

Stream流的filter方法.png

  • 示例:
  1. package com.sunxiaping.jdk8;
  2. import java.util.stream.Stream;
  3. /**
  4. * filter
  5. */
  6. public class LambdaDemo11 {
  7. public static void main(String[] args) {
  8. Stream<String> stream = Stream.of("张三", "李四", "王五", "赵六", "田七", "王八");
  9. stream.filter(s -> s.contains("张")).forEach(System.out::println);
  10. }
  11. }

3.11.9 Stream流中的limit方法

  • Stream流中的limit方法可以对流进行截取,只取前n个:参数是一个long类型,如果集合当前长度大于参数则进行截取,否则不进行任何操作。
  1. public interface Stream<T> extends BaseStream<T, Stream<T>> {
  2. Stream<T> limit(long maxSize);
  3. //略
  4. }

Stream流的limit方法.png

  • 示例:
  1. package com.sunxiaping.jdk8;
  2. import java.util.stream.Stream;
  3. /**
  4. * limit
  5. */
  6. public class LambdaDemo11 {
  7. public static void main(String[] args) {
  8. Stream<String> stream = Stream.of("张三", "李四", "王五", "赵六", "田七", "王八");
  9. stream.limit(3).forEach(System.out::println);
  10. }
  11. }

3.11.10 Stream流中的skip方法

  • 如果希望跳过前n个元素,可以使用skip方法获取一个截取之后的新流:
  1. public interface Stream<T> extends BaseStream<T, Stream<T>> {
  2. Stream<T> skip(long n);
  3. //略
  4. }
  • 如果流当前的长度大于n,则跳过前n个;否则将会得到一个长度为0的空流。

Stream流中的skip方法.png

  • 示例:
  1. package com.sunxiaping.jdk8;
  2. import java.util.stream.Stream;
  3. /**
  4. * skip
  5. */
  6. public class LambdaDemo11 {
  7. public static void main(String[] args) {
  8. Stream<String> stream = Stream.of("张三", "李四", "王五", "赵六", "田七", "王八");
  9. stream.skip(3).forEach(System.out::println);
  10. }
  11. }

3.11.11 Stream流中的map方法

  • 如果需要将流中的元素映射到另一个流中,可以使用map方法。
  1. public interface Stream<T> extends BaseStream<T, Stream<T>> {
  2. <R> Stream<R> map(Function<? super T, ? extends R> mapper);
  3. //略
  4. }
  • 该接口需要一个Function函数式接口参数,可以将当前流中的T类型转换为另一种R类型的流。
  • 使用场景:
    • JDK8 - 图49转换流中的数据格式。
    • JDK8 - 图50提取流中的对象属性。
  • 示例:
  1. package com.sunxiaping.jdk8;
  2. import java.util.stream.Stream;
  3. /**
  4. * map
  5. */
  6. public class LambdaDemo11 {
  7. public static void main(String[] args) {
  8. Stream<String> stream = Stream.of("1", "2", "3", "4", "5", "6");
  9. stream.map(Integer::parseInt).forEach(System.out::println);
  10. }
  11. }

3.11.12 Stream流中的flatMap方法

  • Stream流中的flatMap方法是一个维度升降的方法。
  1. public interface Stream<T> extends BaseStream<T, Stream<T>> {
  2. <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);
  3. //略
  4. }
  • 示例:
  1. package com.sunxiaping.jdk8;
  2. import java.util.Arrays;
  3. import java.util.stream.Stream;
  4. /**
  5. * flatMap
  6. */
  7. public class LambdaDemo11 {
  8. public static void main(String[] args) {
  9. Stream<String> stream = Stream.of("Hello", "World");
  10. stream.map(s -> s.split("")).flatMap(Arrays::stream).forEach(System.out::println);
  11. }
  12. }

3.11.13 Stream流中的sorted方法

  • 如果需要将数据排序,可以使用sorted方法。
  1. public interface Stream<T> extends BaseStream<T, Stream<T>> {
  2. Stream<T> sorted();
  3. Stream<T> sorted(Comparator<? super T> comparator);
  4. //略
  5. }
  • 示例:
  1. package com.sunxaiping.jdk8;
  2. import java.util.ArrayList;
  3. import java.util.Collections;
  4. import java.util.Comparator;
  5. import java.util.List;
  6. public class LambdaDemo11 {
  7. public static void main(String[] args) {
  8. List<Integer> list = new ArrayList<>();
  9. Collections.addAll(list, 1, -1, 10, 0, 100, 55);
  10. //自然排序
  11. list.stream().sorted().forEach(System.out::println);
  12. //逆序
  13. list.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println);
  14. }
  15. }

3.11.14 Stream流中的distinct方法

  • 如果需要去除重复数据,可以使用distinct方法。
  1. public interface Stream<T> extends BaseStream<T, Stream<T>> {
  2. Stream<T> distinct();
  3. //略
  4. }

Stream流中的distinct方法.png

  • 示例:
  1. package com.sunxaiping.jdk8;
  2. import java.util.ArrayList;
  3. import java.util.Collections;
  4. import java.util.List;
  5. public class LambdaDemo11 {
  6. public static void main(String[] args) {
  7. List<Integer> list = new ArrayList<>();
  8. Collections.addAll(list, 1, -1, 10, 0, 10, 55);
  9. list.stream().distinct().forEach(System.out::println);
  10. }
  11. }

3.11.15 Stream流中的match方法

  • 如果需要判断数据是否匹配指定的条件,可以使用match相关方法。
  1. public interface Stream<T> extends BaseStream<T, Stream<T>> {
  2. //元素是否全部满足条件
  3. boolean anyMatch(Predicate<? super T> predicate);
  4. //元素是否满足任意一个条件
  5. boolean allMatch(Predicate<? super T> predicate);
  6. //元素是否全部不满足条件
  7. boolean noneMatch(Predicate<? super T> predicate);
  8. //略
  9. }
  • 示例:
  1. package com.sunxaiping.jdk8;
  2. import java.util.ArrayList;
  3. import java.util.Collections;
  4. import java.util.List;
  5. public class LambdaDemo11 {
  6. public static void main(String[] args) {
  7. List<Integer> list = new ArrayList<>();
  8. Collections.addAll(list, 1, -1, 10, 0, 10, 55);
  9. boolean b = list.stream().allMatch((e) -> e > 5);
  10. if (b) {
  11. System.out.println("元素是否满足都>5");
  12. }
  13. b = list.stream().anyMatch((e) -> e > 5);
  14. if (b) {
  15. System.out.println("元素是否满足任意元素>5");
  16. }
  17. b = list.stream().noneMatch(e -> e > 5);
  18. if (b) {
  19. System.out.println("元素是否全部不小于5");
  20. }
  21. }
  22. }

3.11.16 Stream流中的find方法

  • 如果需要找到某些数据,可以使用find相关方法:
  1. public interface Stream<T> extends BaseStream<T, Stream<T>> {
  2. //获取Stream流中的第一个元素
  3. Optional<T> findFirst();
  4. //获取Stream流中的第一个元素
  5. Optional<T> findAny();
  6. //略
  7. }

Stream流中的find方法.png

  • 示例:
  1. package com.sunxaiping.jdk8;
  2. import java.util.ArrayList;
  3. import java.util.Collections;
  4. import java.util.List;
  5. import java.util.Optional;
  6. public class LambdaDemo11 {
  7. public static void main(String[] args) {
  8. List<Integer> list = new ArrayList<>();
  9. Collections.addAll(list, 1, -1, 10, 0, 10, 55);
  10. Optional<Integer> first = list.stream().findFirst();
  11. System.out.println("first = " + first.get());
  12. Optional<Integer> any = list.stream().findAny();
  13. System.out.println("any = " + any.get());
  14. }
  15. }

3.11.17 Stream流中的max和min方法

  • 如果需要获取最大值和最小值,可以使用max和min方法。
  1. public interface Stream<T> extends BaseStream<T, Stream<T>> {
  2. //获取Stream流中的最大值
  3. Optional<T> max(Comparator<? super T> comparator);
  4. //获取Stream流中的最小值
  5. Optional<T> min(Comparator<? super T> comparator);
  6. //略
  7. }

Stream流中的max方法和min方法.png

  • 示例:
  1. package com.sunxaiping.jdk8;
  2. import java.util.ArrayList;
  3. import java.util.Collections;
  4. import java.util.List;
  5. import java.util.Optional;
  6. public class LambdaDemo11 {
  7. public static void main(String[] args) {
  8. List<Integer> list = new ArrayList<>();
  9. Collections.addAll(list, 1, -1, 10, 0, 10, 55);
  10. Optional<Integer> max = list.stream().max(Integer::compareTo);
  11. System.out.println("max = " + max.get());
  12. Optional<Integer> min = list.stream().min(Integer::compareTo);
  13. System.out.println("min = " + min.get());
  14. }
  15. }

3.11.18 Stream流中的reduce方法

  • 如果需要将所有数据归纳到一个数据,可以使用reduce方法。
  1. public interface Stream<T> extends BaseStream<T, Stream<T>> {
  2. //获取Stream流中的最大值
  3. T reduce(T identity, BinaryOperator<T> accumulator);
  4. //获取Stream流中的最小值
  5. Optional<T> reduce(BinaryOperator<T> accumulator);
  6. //略
  7. }

Stream流中的reduce方法.png

  • 示例:
  1. package com.sunxaiping.jdk8;
  2. import java.util.stream.Stream;
  3. public class LambdaDemo11 {
  4. public static void main(String[] args) {
  5. Stream<Integer> stream = Stream.of(1, -5, 9, 100, 0);
  6. //第一个参数是默认值
  7. //第二个参数:对数据进行处理的方式
  8. Integer reduce = stream.reduce(0, Integer::sum);
  9. System.out.println("reduce = " + reduce);
  10. }
  11. }

3.11.19 Stream流中的mapToInt方法

  • 如果需要将Stream<Integer>中的Integer类型转成int类型,可以使用mapToInt方法。
  1. public interface Stream<T> extends BaseStream<T, Stream<T>> {
  2. //获取Stream流中的最大值
  3. IntStream mapToInt(ToIntFunction<? super T> mapper);
  4. //略
  5. }

Stream.png

  • 示例:
  1. package com.sunxiaping.jdk8;
  2. import java.util.stream.IntStream;
  3. import java.util.stream.Stream;
  4. /**
  5. * mapToInt
  6. */
  7. public class LambdaDemo11 {
  8. public static void main(String[] args) {
  9. //Integer占用的内存比int多,在Stream流操作中会自动装箱和拆箱
  10. Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
  11. //操作
  12. stream.filter(n -> n > 3).forEach(System.out::println);
  13. //mapToInt将Stream流中的Integer变为int
  14. //IntStream:内部操作的是int类型的数据,节省内存,减少自动装箱和拆箱
  15. IntStream intStream = Stream.of(1, 2, 3, 4, 5).mapToInt(Integer::intValue);
  16. intStream.filter(n -> n > 3).forEach(System.out::println);
  17. }
  18. }

3.11.20 Stream流中的concat方法

  • 如果有两个流,希望合并成一个流,那么就可以使用Stream接口中的静态方法concat。
  1. public interface Stream<T> extends BaseStream<T, Stream<T>> {
  2. //将两个流合并成一个流
  3. public static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b) {
  4. Objects.requireNonNull(a);
  5. Objects.requireNonNull(b);
  6. @SuppressWarnings("unchecked")
  7. Spliterator<T> split = new Streams.ConcatSpliterator.OfRef<>(
  8. (Spliterator<T>) a.spliterator(), (Spliterator<T>) b.spliterator());
  9. Stream<T> stream = StreamSupport.stream(split, a.isParallel() || b.isParallel());
  10. return stream.onClose(Streams.composedClose(a, b));
  11. }
  12. //略
  13. }
  • 示例:
  1. package com.sunxiaping.jdk8;
  2. import java.util.stream.Stream;
  3. /**
  4. * concat
  5. */
  6. public class LambdaDemo11 {
  7. public static void main(String[] args) {
  8. Stream<Integer> stream1 = Stream.of(1, 2, 3);
  9. Stream<Integer> stream2 = Stream.of(4, 5, 6);
  10. //两个流合并之后,不能操作之前的流
  11. Stream<Integer> concat = Stream.concat(stream1, stream2);
  12. concat.forEach(System.out::println);
  13. }
  14. }

3.12 收集Stream结果

3.12.1 Stream流中的结果保存到集合中

  • Stream流提供collect方法,其参数需要一个java.util.stream.Collector<T, A, R> 接口对象来指定收集到那种集合中。java.util.stream.Collectors类提供一些方法,可以作为Collector接口的实例。
  1. public interface Stream<T> extends BaseStream<T, Stream<T>> {
  2. //Stream流中的结果保存到集合中
  3. <R, A> R collect(Collector<? super T, A, R> collector);
  4. //略
  5. }
  • 示例:
  1. package com.sunxiaping.jdk8;
  2. import java.util.ArrayList;
  3. import java.util.HashSet;
  4. import java.util.List;
  5. import java.util.Set;
  6. import java.util.stream.Collectors;
  7. import java.util.stream.Stream;
  8. /**
  9. * Stream流中的结果保存到集合中
  10. */
  11. public class LambdaDemo11 {
  12. public static void main(String[] args) {
  13. Stream<Integer> stream1 = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 0);
  14. //将Stream流中的结果保存到List集合中
  15. List<Integer> list = stream1.collect(Collectors.toList());
  16. list.forEach(System.out::println);
  17. //将Stream流中的结果保存到Set集合中
  18. Stream<Integer> stream2 = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 0);
  19. Set<Integer> set = stream2.collect(Collectors.toSet());
  20. set.forEach(System.out::println);
  21. //将Stream流中的结果保存到ArrayList集合中
  22. Stream<Integer> stream3 = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 0);
  23. ArrayList<Integer> arrayList = stream3.collect(Collectors.toCollection(ArrayList::new));
  24. arrayList.forEach(System.out::println);
  25. //将Stream流中的结果保存到HashSet集合中
  26. Stream<Integer> stream4 = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 0);
  27. HashSet<Integer> hashSet = stream4.collect(Collectors.toCollection(HashSet::new));
  28. hashSet.forEach(System.out::println);
  29. }
  30. }

3.12.2 Stream流中的结果保存到数组中

  • Stream流提供toArray方法,以便将Stream流中的结果保存到数组中。
  1. public interface Stream<T> extends BaseStream<T, Stream<T>> {
  2. //Stream流中的结果保存到数组中
  3. Object[] toArray();
  4. <A> A[] toArray(IntFunction<A[]> generator);
  5. //略
  6. }
  • 示例:
  1. package com.sunxiaping.jdk8;
  2. import java.util.Arrays;
  3. import java.util.stream.Stream;
  4. public class LambdaDemo11 {
  5. public static void main(String[] args) {
  6. //Stream流中的数据转换成Object数组
  7. Stream<Integer> stream1 = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 0);
  8. Object[] array = stream1.toArray();
  9. System.out.println("Stream流转换为Object数组:" + Arrays.toString(array));
  10. //Stream流中的数据转换成String数组
  11. Stream<String> stream2 = Stream.of("1", "2", "3", "4", "5", "6", "7", "8", "9", "0");
  12. String[] strings = stream2.toArray(String[]::new);
  13. System.out.println("Stream流转换为String数组 = " + Arrays.asList(strings));
  14. }
  15. }

3.12.3 对流中数据进行聚合计算

  • 当我们使用Stream流处理数据的时候,可以像数据库的聚合函数一样对某个字段进行操作。比如获取最大值、获取最小值、求和、平均值、统计数量。
  • 示例:
  1. package com.sunxiaping.jdk8;
  2. import java.util.Optional;
  3. import java.util.stream.Collectors;
  4. import java.util.stream.Stream;
  5. /**
  6. * Stream流一旦调用终止方法,就不可以再操作。
  7. */
  8. public class LambdaDemo11 {
  9. public static void main(String[] args) {
  10. //获取Stream流中数据的总数
  11. Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 0);
  12. long count = stream.count();
  13. System.out.println("count = " + count);
  14. //获取Stream流中的最大值
  15. stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 0);
  16. Optional<Integer> max = stream.max(Integer::compareTo);
  17. System.out.println("max = " + max.get());
  18. //获取Stream流中的最小值
  19. stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 0);
  20. Optional<Integer> min = stream.min(Integer::compareTo);
  21. System.out.println("min = " + min.get());
  22. System.out.println("-----------------------------");
  23. stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 0);
  24. Optional<Integer> maxOptional = stream.collect(Collectors.maxBy(Integer::compareTo));
  25. System.out.println("max = " + maxOptional.get());
  26. stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 0);
  27. Optional<Integer> minOptional = stream.collect(Collectors.minBy(Integer::compareTo));
  28. System.out.println("min = " + minOptional.get());
  29. stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 0);
  30. count = stream.collect(Collectors.counting());
  31. System.out.println("count = " + count);
  32. stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 0);
  33. Double avg = stream.collect(Collectors.averagingInt(Integer::intValue));
  34. System.out.println("avg = " + avg);
  35. stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 0);
  36. Integer sum = stream.collect(Collectors.summingInt(Integer::intValue));
  37. System.out.println("sum = " + sum);
  38. }
  39. }

3.12.4 对流中的数据进行分组

  • 当我们使用Stream流处理数据后,可以根据某个属性进行数据分组。
  • 示例:
  1. package com.sunxiaping.jdk8;
  2. public class Person {
  3. private String name;
  4. private Integer age;
  5. private Integer score;
  6. public Person() {
  7. }
  8. public Person(String name, Integer age, Integer score) {
  9. this.name = name;
  10. this.age = age;
  11. this.score = score;
  12. }
  13. public String getName() {
  14. return name;
  15. }
  16. public void setName(String name) {
  17. this.name = name;
  18. }
  19. public Integer getAge() {
  20. return age;
  21. }
  22. public void setAge(Integer age) {
  23. this.age = age;
  24. }
  25. public Integer getScore() {
  26. return score;
  27. }
  28. public void setScore(Integer score) {
  29. this.score = score;
  30. }
  31. @Override
  32. public String toString() {
  33. return "Person{" +
  34. "name='" + name + '\'' +
  35. ", age=" + age +
  36. ", score=" + score +
  37. '}';
  38. }
  39. }
  1. package com.sunxiaping.jdk8;
  2. import java.util.List;
  3. import java.util.Map;
  4. import java.util.stream.Collectors;
  5. import java.util.stream.Stream;
  6. /**
  7. * Stream流一旦调用终止方法,就不可以再操作。
  8. */
  9. public class LambdaDemo11 {
  10. public static void main(String[] args) {
  11. Stream<Person> stream = Stream.of(
  12. new Person("赵丽颖", 52, 95),
  13. new Person("杨颖", 56, 86),
  14. new Person("迪丽热巴", 56, 99),
  15. new Person("柳岩", 52, 77));
  16. //根据年龄分组
  17. Map<Integer, List<Person>> map = stream.collect(Collectors.groupingBy(Person::getAge));
  18. map.forEach((k, v) -> {
  19. System.out.println("年龄 = " + k);
  20. List<Person> personList = v;
  21. System.out.println("person = " + personList);
  22. });
  23. }
  24. }

3.12.5 对流中的数据进行多级分组

  • 还可以对流中的数据进行多级分组。
  • 示例:
  1. package com.sunxiaping.jdk8;
  2. public class Person {
  3. private String name;
  4. private Integer age;
  5. private Integer score;
  6. private String sex;
  7. public Person() {
  8. }
  9. public Person(String name, Integer age, Integer score, String sex) {
  10. this.name = name;
  11. this.age = age;
  12. this.score = score;
  13. this.sex = sex;
  14. }
  15. public String getName() {
  16. return name;
  17. }
  18. public void setName(String name) {
  19. this.name = name;
  20. }
  21. public Integer getAge() {
  22. return age;
  23. }
  24. public void setAge(Integer age) {
  25. this.age = age;
  26. }
  27. public Integer getScore() {
  28. return score;
  29. }
  30. public void setScore(Integer score) {
  31. this.score = score;
  32. }
  33. public String getSex() {
  34. return sex;
  35. }
  36. public void setSex(String sex) {
  37. this.sex = sex;
  38. }
  39. @Override
  40. public String toString() {
  41. return "Person{" +
  42. "name='" + name + '\'' +
  43. ", age=" + age +
  44. ", score=" + score +
  45. ", sex='" + sex + '\'' +
  46. '}';
  47. }
  48. }
  1. package com.sunxiaping.jdk8;
  2. import java.util.List;
  3. import java.util.Map;
  4. import java.util.stream.Collectors;
  5. import java.util.stream.Stream;
  6. /**
  7. * Stream流一旦调用终止方法,就不可以再操作。
  8. */
  9. public class LambdaDemo11 {
  10. public static void main(String[] args) {
  11. Stream<Person> stream = Stream.of(
  12. new Person("赵丽颖", 52, 95, "女"),
  13. new Person("杨颖", 56, 86, "女"),
  14. new Person("迪丽热巴", 56, 99, "女"),
  15. new Person("黄晓明", 52, 77, "男"));
  16. //先根据性别分组,性别相同再按照年龄分组
  17. Map<String, Map<Integer, List<Person>>> map = stream.collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getAge)));
  18. map.forEach((sex, v1) -> {
  19. System.out.println("sex = " + sex);
  20. Map<Integer, List<Person>> map1 = v1;
  21. map1.forEach((age, v2) -> {
  22. System.out.print(age + "---->");
  23. System.out.println("personList = " + v2);
  24. });
  25. });
  26. }
  27. }

3.12.6 对流中的数据进行分区

  • Collectors的partitioningBy方法会根据值是否为true,把流中的数据分为两个部分,一个是true的部分,一个是false的部分。

对流中的数据进行分区.png

  • 示例:
  1. package com.sunxiaping.jdk8;
  2. public class Person {
  3. private String name;
  4. private Integer age;
  5. private Integer score;
  6. public Person() {
  7. }
  8. public Person(String name, Integer age, Integer score) {
  9. this.name = name;
  10. this.age = age;
  11. this.score = score;
  12. }
  13. public String getName() {
  14. return name;
  15. }
  16. public void setName(String name) {
  17. this.name = name;
  18. }
  19. public Integer getAge() {
  20. return age;
  21. }
  22. public void setAge(Integer age) {
  23. this.age = age;
  24. }
  25. public Integer getScore() {
  26. return score;
  27. }
  28. public void setScore(Integer score) {
  29. this.score = score;
  30. }
  31. @Override
  32. public String toString() {
  33. return "Person{" +
  34. "name='" + name + '\'' +
  35. ", age=" + age +
  36. ", score=" + score +
  37. '}';
  38. }
  39. }
  1. package com.sunxiaping.jdk8;
  2. import java.util.List;
  3. import java.util.Map;
  4. import java.util.stream.Collectors;
  5. import java.util.stream.Stream;
  6. /**
  7. * Stream流一旦调用终止方法,就不可以再操作。
  8. */
  9. public class LambdaDemo11 {
  10. public static void main(String[] args) {
  11. Stream<Person> stream = Stream.of(
  12. new Person("赵丽颖", 52, 95),
  13. new Person("杨颖", 56, 86),
  14. new Person("迪丽热巴", 56, 99),
  15. new Person("黄晓明", 52, 77));
  16. Map<Boolean, List<Person>> map = stream.collect(Collectors.partitioningBy(p -> p.getScore() > 90));
  17. map.forEach((k,v)->{
  18. System.out.println("k = " + k);
  19. System.out.println("v = " + v);
  20. });
  21. }
  22. }

3.12.7 对流中的数据进行拼接

  • Collectors的joining方法会根据指定的连接符,将所有元素连接成一个字符串。
  • 示例:
  1. package com.sunxiaping.jdk8;
  2. public class Person {
  3. private String name;
  4. private Integer age;
  5. private Integer score;
  6. public Person() {
  7. }
  8. public Person(String name, Integer age, Integer score) {
  9. this.name = name;
  10. this.age = age;
  11. this.score = score;
  12. }
  13. public String getName() {
  14. return name;
  15. }
  16. public void setName(String name) {
  17. this.name = name;
  18. }
  19. public Integer getAge() {
  20. return age;
  21. }
  22. public void setAge(Integer age) {
  23. this.age = age;
  24. }
  25. public Integer getScore() {
  26. return score;
  27. }
  28. public void setScore(Integer score) {
  29. this.score = score;
  30. }
  31. @Override
  32. public String toString() {
  33. return "Person{" +
  34. "name='" + name + '\'' +
  35. ", age=" + age +
  36. ", score=" + score +
  37. '}';
  38. }
  39. }
  1. package com.sunxiaping.jdk8;
  2. import java.util.stream.Collectors;
  3. import java.util.stream.Stream;
  4. /**
  5. * Stream流一旦调用终止方法,就不可以再操作。
  6. */
  7. public class LambdaDemo11 {
  8. public static void main(String[] args) {
  9. Stream<Person> stream = Stream.of(
  10. new Person("赵丽颖", 52, 95),
  11. new Person("杨颖", 56, 86),
  12. new Person("迪丽热巴", 56, 99),
  13. new Person("黄晓明", 52, 77));
  14. String str = stream.map(Person::getName).collect(Collectors.joining("><", "(#^.^#)", "^_^"));
  15. System.out.println("str = " + str);
  16. }
  17. }

3.13 并行的Stream流

3.13.1 了解串行的Stream流

  • 目前使用的Stream流是串行的,就是在一个线程上执行。
  1. package com.sunxiaping.jdk8;
  2. import java.util.stream.Stream;
  3. /**
  4. * Stream流一旦调用终止方法,就不可以再操作。
  5. */
  6. public class LambdaDemo11 {
  7. public static void main(String[] args) {
  8. Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 0);
  9. long count = stream.filter(s -> {
  10. System.out.println(Thread.currentThread().getName() + "---" + s);
  11. return true;
  12. }).count();
  13. System.out.println("count = " + count);
  14. }
  15. }

3.13.2 获取并行的Stream流的两种方式

  • 直接获取并行的Stream流。
  1. package com.sunxiaping.jdk8;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import java.util.stream.Stream;
  5. /**
  6. * Stream流一旦调用终止方法,就不可以再操作。
  7. */
  8. public class LambdaDemo11 {
  9. public static void main(String[] args) {
  10. List<String> list = new ArrayList<>();
  11. //直接获取并行的Stream流
  12. Stream<String> parallelStream = list.parallelStream();
  13. }
  14. }
  • 将串行流转成并行流。
  1. package com.sunxiaping.jdk8;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import java.util.stream.Stream;
  5. /**
  6. * Stream流一旦调用终止方法,就不可以再操作。
  7. */
  8. public class LambdaDemo11 {
  9. public static void main(String[] args) {
  10. List<String> list = new ArrayList<>();
  11. //串行流转成并行流
  12. Stream<String> parallel = list.stream().parallel();
  13. }
  14. }

3.14 Optional类的使用

3.14.1 以前对null的处理

  1. package com.sunxiaping.jdk8;
  2. public class OptionalDemo {
  3. public static void main(String[] args) {
  4. String username = null;
  5. if(null != username){
  6. System.out.println("username = " + username);
  7. }
  8. }
  9. }

3.14.2 Optional类的介绍

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

Optional类的介绍.png

  • Optional类的创建方式:
  1. //创建一个Optional实例
  2. public static <T> Optional<T> of(T value);
  1. //创建一个空的Optional实例
  2. public static<T> Optional<T> empty();
  1. //如果value不为null,则创建Optional实例,否则创建空的Optional实例
  2. public static <T> Optional<T> ofNullable(T value);
  • Optional类的常用方法:
  1. //判断是否包含值,如果包含值返回true,否则返回false
  2. public boolean isPresent();
  1. //如果Optional有值则将其抛出NoSuchElementException异常
  2. public T get();
  1. //如果存在包含值,返回包含值,否则返回参数other
  2. public T orElse(T other) ;
  1. //如果存在包含值,返回包含值,否则返回other获取的值
  2. public T orElseGet(Supplier<? extends T> other);
  1. //如果存在包含值,对其处理,并返回处理后的Optional,否则返回Optional.empty()
  2. public<U> Optional<U> map(Function<? super T, ? extends U> mapper);

3.14.3 Optional类的基本使用

  • 示例:
  1. package com.sunxiaping.jdk8;
  2. import org.junit.Test;
  3. import java.util.Optional;
  4. public class OptionalDemo {
  5. /**
  6. * 创建Optional实例
  7. * Optional.of(T value):不能传null,否则报错
  8. */
  9. @Test
  10. public void testCreateOptional1() {
  11. Optional<String> optional = Optional.of("凤姐");
  12. System.out.println("optional.get() = " + optional.get());
  13. }
  14. /**
  15. * 创建Optional实例
  16. * Optional.empty() 创建一个空的Optional
  17. */
  18. @Test
  19. public void testCreateOptional2() {
  20. Optional<Object> empty = Optional.empty();
  21. System.out.println("empty = " + empty);
  22. }
  23. /**
  24. * 创建Optional实例
  25. * Optional.ofNullable(T value):如果value是null,则返回Optional.empty();如果value有值,则返回Optional.of(T value)
  26. */
  27. @Test
  28. public void testCreateOptional3() {
  29. Optional<Object> optional = Optional.ofNullable(null);
  30. System.out.println("optional = " + optional);
  31. optional = Optional.ofNullable("你好啊");
  32. System.out.println("optional = " + optional);
  33. }
  34. }
  • 示例:
  1. package com.sunxiaping.jdk8;
  2. import org.junit.Test;
  3. import java.util.Optional;
  4. public class OptionalDemo {
  5. /**
  6. * 判断Optional类中是否有值
  7. */
  8. @Test
  9. public void test() {
  10. Optional<Object> empty = Optional.empty();
  11. if (empty.isPresent()) {
  12. System.out.println("Optional类中有值");
  13. } else {
  14. System.out.println("Optional类中没有值");
  15. }
  16. }
  17. }
  • 示例:
  1. package com.sunxiaping.jdk8;
  2. import org.junit.Test;
  3. import java.util.Optional;
  4. public class OptionalDemo {
  5. /**
  6. * 获取Optional类中的值
  7. */
  8. @Test
  9. public void test() {
  10. Optional<String> optional = Optional.ofNullable("你好,世界");
  11. if (optional.isPresent()) {
  12. //get()方法,可以用来获取Optional类中的值,如果有值就返回具体值,否则就报错。
  13. //一般get()方法配置isPresent()方法使用
  14. String str = optional.get();
  15. System.out.println("str = " + str);
  16. }
  17. }
  18. }

3.14.4 Optional类的高级使用

  • 示例:
  1. package com.sunxiaping.jdk8;
  2. import org.junit.Test;
  3. import java.util.Optional;
  4. public class OptionalDemo {
  5. /**
  6. * 获取Optional类中的值
  7. */
  8. @Test
  9. public void test() {
  10. Optional<Object> optional = Optional.empty();
  11. //orElse:如果Optional中有值,就返回Optional中的值。否则返回orElse方法中参数指定的值
  12. Object obj = optional.orElse("如花");
  13. System.out.println("obj = " + obj);
  14. }
  15. }
  • 示例:
  1. package com.sunxiaping.jdk8;
  2. import org.junit.Test;
  3. import java.util.Optional;
  4. public class OptionalDemo {
  5. /**
  6. * 获取Optional类中的值
  7. */
  8. @Test
  9. public void test() {
  10. Optional<String> optional = Optional.of("凤姐");
  11. //ifPresent:如果有值,就调用参数
  12. optional.ifPresent((s) -> {
  13. System.out.println("有值:" + s);
  14. });
  15. //ifPresentOrElse在JDK9以后才有
  16. //ifPresentOrElse第一个参数表示如果有值,做什么
  17. //ifPresentOrElse第二个参数表示如果没有值,做什么
  18. optional.ifPresentOrElse(s -> {
  19. System.out.println("s = " + s);
  20. }, () -> {
  21. System.out.println("没有值");
  22. });
  23. }
  24. }
  • 示例:
  1. package com.sunxiaping.jdk8;
  2. import org.junit.Test;
  3. import java.util.Optional;
  4. public class OptionalDemo {
  5. /**
  6. * 获取Optional类中的值
  7. */
  8. @Test
  9. public void test() {
  10. //将Person中的用户名转成大写返回
  11. Person person = null;
  12. person = new Person("hello world", 18, 99);
  13. String name = getTraditionUpperName(person);
  14. System.out.println("name = " + name);
  15. name = getOptionalUpperName(person);
  16. System.out.println("name = " + name);
  17. }
  18. public String getOptionalUpperName(Person person) {
  19. return Optional.ofNullable(person).map(Person::getName).map(String::toUpperCase).orElse(null);
  20. }
  21. /**
  22. * 传统方式 实现需求
  23. *
  24. * @param person
  25. * @return
  26. */
  27. public String getTraditionUpperName(Person person) {
  28. if (null != person) {
  29. String name = person.getName();
  30. if (null != name) {
  31. return name.toUpperCase();
  32. }
  33. }
  34. return null;
  35. }
  36. }

3.15 JDK8新的时间和日期API

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

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

3.15.2 新日期时间API介绍

  • JDK8中增加了一套全新的日期时间API,这套API设计合理,是线程安全的。
  • 新的日期和时间API位于java.time包中,下面是一些管件类。
    • JDK8 - 图61LocalDate:表示日期,包含年、月、日,格式为2011-11-11。
    • JDK8 - 图62LocalTIme:表示时间,包含时、分、秒,格式为14:28:40.426000700。
    • JDK8 - 图63LocalDateTime:表示日期时间,包含年、月、日、时、分、秒,格式为2020-09-08T14:29:37.546506。
    • JDK8 - 图64DateTimeFormatter:日期时间格式化类。
    • JDK8 - 图65Instant:时间戳,表示一个特定的时间瞬间。
    • JDK8 - 图66Duration:用于计算2个时间(LocalTime,Instant等)的距离。
    • JDK8 - 图67Period:用于计算2个日期(LocalDate)的距离。
    • JDK8 - 图68ZoneDateTime:包含时区的时间。
  • Java中使用的历法是ISO 8601日历系统,它是世界民用历法,也就是我们所说的公历。平年有365天,闰年有366天。此外Java8还提供了4条其他历法,分别是:
    • JDK8 - 图69ThaiBuddhistDate:泰国佛教历法。
    • JDK8 - 图70MinguoDate:中华民国历法。
    • JDK8 - 图71JapaneseDate:日本历法。
    • JDK8 - 图72HijrahDate:伊斯兰历法。

3.15.3 JDK8的日期和时间类

  • LocalDate、LocalTime、LocalDateTime类的实例是不可变的对象,分别表示ISO 8601日历系统的日期、时间、日期和时间。它们提供了简单的日期或时间,并不包含当前的时间信息,也不包含和时区相关的信息。
  • 示例:
  1. package com.sunxiaping.jdk8;
  2. import org.junit.Test;
  3. import java.time.LocalDate;
  4. import java.time.LocalDateTime;
  5. import java.time.LocalTime;
  6. public class DateTimeDemo {
  7. @Test
  8. public void testLocalDate() {
  9. //LocalDate:表示日期,有年、月、日
  10. LocalDate now = LocalDate.now();
  11. System.out.println("now = " + now);
  12. LocalDate date = LocalDate.of(2011, 11, 11);
  13. System.out.println("date = " + date);
  14. int year = now.getYear();
  15. System.out.println("year = " + year);
  16. int month = now.getMonth().getValue();
  17. System.out.println("month = " + month);
  18. month = now.getMonthValue();
  19. System.out.println("month = " + month);
  20. int day = now.getDayOfMonth();
  21. System.out.println("day = " + day);
  22. }
  23. @Test
  24. public void testLocalTime() {
  25. //LocalTime:表示时间,有时、分、秒
  26. LocalTime now = LocalTime.now();
  27. System.out.println("now = " + now);
  28. LocalTime time = LocalTime.of(15, 30, 11);
  29. System.out.println("time = " + time);
  30. int hour = now.getHour();
  31. System.out.println("hour = " + hour);
  32. int minute = now.getMinute();
  33. System.out.println("minute = " + minute);
  34. int second = now.getSecond();
  35. System.out.println("second = " + second);
  36. int nano = now.getNano();
  37. System.out.println("nano = " + nano);
  38. }
  39. @Test
  40. public void testLocalDateTime() {
  41. //LocalDateTime:表示日期时间,有年、月、日、时、分、秒
  42. LocalDateTime now = LocalDateTime.now();
  43. System.out.println("now = " + now);
  44. LocalDateTime dateTime = LocalDateTime.of(2011, 11, 11, 11, 11, 11);
  45. System.out.println("dateTime = " + dateTime);
  46. int year = now.getYear();
  47. System.out.println("year = " + year);
  48. int month = now.getMonthValue();
  49. System.out.println("month = " + month);
  50. month = now.getMonth().getValue();
  51. System.out.println("month = " + month);
  52. int day = now.getDayOfMonth();
  53. System.out.println("day = " + day);
  54. int hour = now.getHour();
  55. System.out.println("hour = " + hour);
  56. int minute = now.getMinute();
  57. System.out.println("minute = " + minute);
  58. int second = now.getSecond();
  59. System.out.println("second = " + second);
  60. int nano = now.getNano();
  61. System.out.println("nano = " + nano);
  62. }
  63. /**
  64. * 修改时间
  65. */
  66. @Test
  67. public void testLocalDateTime2() {
  68. LocalDateTime now = LocalDateTime.now();
  69. LocalDateTime localDateTime = now.withYear(2021).withMinute(5);
  70. System.out.println("now = " + now);
  71. System.out.println("localDateTime = " + localDateTime);
  72. LocalDateTime localDateTime1 = now.plusYears(1);
  73. System.out.println("localDateTime1 = " + localDateTime1);
  74. }
  75. /**
  76. * 比较时间
  77. */
  78. @Test
  79. public void testLocalDateTime3() {
  80. LocalDateTime now = LocalDateTime.now();
  81. LocalDateTime localDateTime = LocalDateTime.now().plusYears(1);
  82. boolean before = now.isBefore(localDateTime);
  83. System.out.println("before = " + before);
  84. }
  85. }

3.15.4 JDK8的时间格式化和解析

  • 通过java.time.format.DateTimeFormatter类可以进行日期时间解析和格式化。
  • 示例:
  1. package com.sunxiaping.jdk8;
  2. import org.junit.Test;
  3. import java.time.LocalDateTime;
  4. import java.time.format.DateTimeFormatter;
  5. public class DateTimeFormatterDemo {
  6. @Test
  7. public void test() {
  8. DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
  9. LocalDateTime now = LocalDateTime.now();
  10. //格式化 调用LocalDateTime
  11. String format = now.format(df);
  12. System.out.println("format = " + format);
  13. //解析 调用LocalDateTime
  14. LocalDateTime parse = LocalDateTime.parse(format, df);
  15. System.out.println("parse = " + parse);
  16. //格式化
  17. format = df.format(now);
  18. System.out.println("format = " + format);
  19. //解析
  20. parse = df.parse(format, LocalDateTime::from);
  21. System.out.println("parse = " + parse);
  22. }
  23. }

3.15.5 JDK8的Instant类

  • Instant时间戳/时间线,内部保存了从1970年1月1日 00:00:00 以来的秒和纳秒。
  • 示例:
  1. package com.sunxaiping.jdk8;
  2. import org.junit.Test;
  3. import java.time.Instant;
  4. public class DateTimeDemo {
  5. @Test
  6. public void test() {
  7. //Instance内部保存了秒和纳秒,一般不是给用户使用的,而是方便我们程序做一些统计
  8. Instant now = Instant.now();
  9. System.out.println("now = " + now);
  10. Instant instant = now.plusSeconds(20);
  11. System.out.println("instant = " + instant);
  12. long epochSecond = now.getEpochSecond();
  13. System.out.println("epochSecond = " + epochSecond);
  14. int nano = now.getNano();
  15. System.out.println("nano = " + nano);
  16. }
  17. }

3.15.6 JDK8的计算日期时间差类

  • Duration:用于计算2个时间(LocalTime,Instant等)的距离。
  • Period:用于计算2个日期(LocalDate)的距离。
  • 示例:
  1. package com.sunxaiping.jdk8;
  2. import org.junit.Test;
  3. import java.time.Duration;
  4. import java.time.LocalDate;
  5. import java.time.LocalTime;
  6. import java.time.Period;
  7. public class DateTimeDemo {
  8. @Test
  9. public void test() {
  10. Duration duration = Duration.between(LocalTime.now(), LocalTime.now().plusSeconds(60));
  11. System.out.println("相差天 = " + duration.toDays());
  12. System.out.println("相差小时 = " + duration.toHours());
  13. System.out.println("相差分钟 = " + duration.toMinutes());
  14. System.out.println("相差毫秒 = " + duration.toNanos());
  15. System.out.println("相差秒 = " + duration.getSeconds());
  16. Period period = Period.between(LocalDate.now(), LocalDate.now().plusDays(2).plusMonths(2));
  17. System.out.println("相差年 = " + period.getYears());
  18. System.out.println("相差月 = " + period.getMonths());
  19. System.out.println("相差日 = " + period.getDays());
  20. }
  21. }

3.15.7 JDK8的时间校正器

  • 有时我们可能需要获取例如:将日期调整到下一个月的第一天等操作。可以通过时间校正器来进行。
  • TemporalAdjuster:时间校正器。
  • TemporalAdjusters:该类通过静态方法提供了大量的常用TemporalAdjuster的实现。
  • 示例:
  1. package com.sunxaiping.jdk8;
  2. import org.junit.Test;
  3. import java.time.LocalDateTime;
  4. import java.time.temporal.TemporalAdjusters;
  5. public class DateTimeDemo {
  6. @Test
  7. public void test() {
  8. LocalDateTime now = LocalDateTime.now();
  9. //将日期和时间调整到"下一个月的第一天"
  10. LocalDateTime localDateTime = now.with(TemporalAdjusters.firstDayOfNextMonth());
  11. System.out.println("localDateTime = " + localDateTime);
  12. }
  13. }

3.15.8 JDK8设置日期时间的时区

  • JDK8中加入了对时区的支持,LocalDate、LocalTime、LocalDateTIme是不带时区的,带时区的日期时间类分别是ZonedDate、ZonedTime、ZonedDateTime。
  • 其中每个时区都对应的ID,ID的格式是“区域/城市”,比如:Asia/Shanghai等。
  • ZoneId:该类中包含了所有的时区信息。
  • 示例:
  1. package com.sunxaiping.jdk8;
  2. import org.junit.Test;
  3. import java.time.Clock;
  4. import java.time.LocalDateTime;
  5. import java.time.ZoneId;
  6. import java.time.ZonedDateTime;
  7. public class DateTimeDemo {
  8. @Test
  9. public void test() {
  10. //获取所有的时区信息
  11. ZoneId.getAvailableZoneIds().forEach(System.out::println);
  12. //获取当前默认的时区
  13. String id = ZoneId.systemDefault().getId();
  14. System.out.println("默认的时区id = " + id);
  15. //不带时区,获取计算机的当前时间
  16. LocalDateTime now = LocalDateTime.now();
  17. System.out.println("不带时区的当前时间 = " + now);
  18. //操作带时区的类
  19. ZonedDateTime bz = ZonedDateTime.now(Clock.systemUTC());
  20. System.out.println("世界标准时间 = " + bz);
  21. ZonedDateTime time = ZonedDateTime.now(ZoneId.systemDefault());
  22. System.out.println("带时区的当前时间 = " + time);
  23. //修改时区
  24. ZonedDateTime dateTime = ZonedDateTime.now(ZoneId.of("America/Los_Angeles"));
  25. //withZoneSameInstant既改时区,也改时间
  26. ZonedDateTime zonedDateTime = dateTime.withZoneSameInstant(ZoneId.systemDefault());
  27. //withZoneSameLocal只改时区
  28. ZonedDateTime zonedDateTime1 = dateTime.withZoneSameLocal(ZoneId.systemDefault());
  29. System.out.println("修改时区和时间 = " + zonedDateTime);
  30. System.out.println("只改时区 = " + zonedDateTime1);
  31. }
  32. }

3.16 重复注解

  • 自从JDK5中引入注解依赖,注解开始变得非常流行,并在各个框架和项目中被广泛使用。不过注解有一个很大的限制是:在同一个地方不能多次使用同一个注解。JDK8引入重复注解的概念,允许在同一个地方多次使用同一个注解。在JDK8中使用@Repeatable注解定义重复注解。
  • 重复注解的使用步骤:
  • JDK8 - 图73定义重复注解的容器注解:
  1. package com.sunxaiping.jdk8;
  2. import java.lang.annotation.Retention;
  3. import java.lang.annotation.RetentionPolicy;
  4. /**
  5. * 定义重复注解的容器
  6. */
  7. @Retention(RetentionPolicy.RUNTIME)
  8. public @interface MyTests {
  9. MyTest[] value();
  10. }
  • JDK8 - 图74定义一个可以重复的注解:
  1. package com.sunxaiping.jdk8;
  2. import java.lang.annotation.Repeatable;
  3. import java.lang.annotation.Retention;
  4. import java.lang.annotation.RetentionPolicy;
  5. /**
  6. * 定义重复注解
  7. */
  8. @Retention(RetentionPolicy.RUNTIME)
  9. @Repeatable(MyTests.class)
  10. public @interface MyTest {
  11. String value();
  12. }
  • JDK8 - 图75配置多个重复的注解:
  1. package com.sunxaiping.jdk8;
  2. import java.io.Serializable;
  3. @MyTest("aa")
  4. @MyTest("bb")
  5. @MyTest("cc")
  6. public class Person implements Serializable {
  7. private String name;
  8. private Integer age;
  9. public String getName() {
  10. return name;
  11. }
  12. public void setName(String name) {
  13. this.name = name;
  14. }
  15. public Integer getAge() {
  16. return age;
  17. }
  18. public void setAge(Integer age) {
  19. this.age = age;
  20. }
  21. @Override
  22. public String toString() {
  23. return "Person{" +
  24. "name='" + name + '\'' +
  25. ", age=" + age +
  26. '}';
  27. }
  28. }
  • JDK8 - 图76解析得到重复注解:
  1. package com.sunxaiping.jdk8;
  2. import java.util.Arrays;
  3. public class RepeatableAnnotationDemo {
  4. public static void main(String[] args) {
  5. //getAnnotationsByType是新增的API,用于获取重复的注解
  6. MyTest[] myTests = Person.class.getAnnotationsByType(MyTest.class);
  7. Arrays.stream(myTests).map(MyTest::value).forEach(System.out::println);
  8. }
  9. }

3.17 类型注解

  • JDK8为@Target元注解新增了两种类型:TYPE_PARAMETER和TYPE_USE。
  • TYPE_PARAMETER:表示该注解能写在类型参数的声明语句中。
  • TYPE_USE:表示注解可以在任何用到类型的地方使用。
  • 示例:
  1. package com.sunxaiping.jdk8;
  2. import java.lang.annotation.ElementType;
  3. import java.lang.annotation.Target;
  4. @Target(ElementType.TYPE_PARAMETER)
  5. public @interface TypeParam {
  6. }
  1. package com.sunxaiping.jdk8;
  2. public class Demo02<@TypeParam T> {
  3. public <@TypeParam E> void test(){
  4. }
  5. }
  • 示例:
  1. package com.sunxaiping.jdk8;
  2. import java.lang.annotation.ElementType;
  3. import java.lang.annotation.Target;
  4. @Target(ElementType.TYPE_USE)
  5. public @interface TypeUse {
  6. }
  1. package com.sunxaiping.jdk8;
  2. public class Demo02<@TypeUse T> {
  3. public <@TypeUse E> void test(){
  4. }
  5. }