java8新特性Lambda和Stream以及函数式接口等新特性介绍

主要内容

1.Lambda 表达式
2.函数式接口
3.方法引用与构造器引用
4.Stream API
5.接口中的默认方法与静态方法
6.新时间日期API
7.其他新特性

Java 8新特性简介

  • 速度更快
  • 速度更快
  • 代码更少(增加了新的语法Lambda 表达式)
  • 强大的Stream API
  • 便于并行
  • 最大化减少空指针异常Optional
  • Nashorn 引擎,允许在 JVM 上运行 JS 应用
    其中最为核心的为Lambda 表达式与Stream API

Lambda 表达式

为什么使用Lambda 表达式?

  Lambda是一个 匿名函数 ,我们可以把 Lambda 表达式理解为是 一段可以传递的代码 (将代码像数据一样进行传递)。使用它可以写出更简洁、更灵活的代码。作为一种更紧凑的代码风格,使 Java 的语言表达能力得到了提升。

从匿名类到 Lambda 的转换举例
package com.atguigu.Lambda;

import org.junit.Test;

import java.util.Comparator;

/**
 * @ClassName LambdaTest
 * @Description Lambda表达式的使用举例
 * @Author wangzhengguo
 * @Date 2020/10/9 10:59
 **/
public class LambdaTest {

    @Test
    public void test1() {
        //匿名内部类
        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                System.out.println("我爱北京天安门");
            }
        };
        r1.run();
        System.out.println("*********************************");

        //Lambda表达式
        Runnable r2 = () -> System.out.println("我爱北京故宫");
        r2.run();
    }

    @Test
    public void test2() {
    	  //原来使用匿名内部类作为参数传递
        Comparator<Integer> com1 = new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return Integer.compare(o1, o2);
            }
        };
        int compare1 = com1.compare(12, 21);
        System.out.println(compare1);
        System.out.println("*********************************");
         //Lambda表达式作为参数传递
        Comparator<Integer> com2 = (o1, o2) -> Integer.compare(o1, o2);
        int compare2 = com2.compare(32, 21);
        System.out.println(compare2);
        System.out.println("*********************************");
        //方法引用
        Comparator<Integer> com3 = Integer::compare;
        int compare3 = com3.compare(32, 21);
        System.out.println(compare3);
    }
}

  Lambda表达式 在 Java 8 语言中引入 的 一 种 新的语法元素和操作符。这个操作符为 " ->" 该操作符被称为 Lambda 操作符或 箭 头操作符 。它将 Lambda 分为两个部分:

  • 左侧:指定了 Lambda 表达式需要的参数列表.
  • 右侧:指定了 Lambda 体 是抽象方法的实现逻辑,也即Lambda 表达式要执行 的功能 。

lamdba表达式的使用:分为6种情况介绍

  • 语法格式一:无参,无返回值,Lambda 体只需一条语句
	@Test
    public void test1() {
        //匿名内部类
        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                System.out.println("我爱北京天安门");
            }
        };
        r1.run();
        System.out.println("*********************************");

        //Lambda表达式
        Runnable r2 = () -> {
            System.out.println("我爱北京故宫");
        };
        r2.run();
    }
  • 语法格式二:Lambda 需要一个参数,但是没有返回值。
 	@Test
    public void test2() {
        Consumer<String> con = new Consumer<String>() {
            @Override
            public void accept(String s) {
                System.out.println(s);
            }
        };
        con.accept("谎言和誓言的区别是什么?");
        System.out.println("*********************************");
        Consumer<String> con1 = (String s) ->{
            System.out.println(s);
        };
        con1.accept("一个是听的人当真了,一个是说的人当真了");
    }
  • 语法格式三:数据类型可以省略,因为可由编译器推断得出,称为"类型推断"
    @Test
    public void test3() {
        Consumer<String> con1 = (String s) -> {
            System.out.println(s);
        };
        con1.accept("一个是听的人当真了,一个是说的人当真了");
        System.out.println("*********************************");
        Consumer<String> con2 = (s) -> {
            System.out.println(s);
        };
        con2.accept("一个是听的人当真了,一个是说的人当真了");
        
        ArrayList<String> list = new ArrayList<>();//类型推断
        int[] arr = {1, 2, 3};//类型推断
    }
    
    • 语法格式四:Lambda 若只需要一个参数时, 参数的小括号可以省略
    @Test
    public void test4() {
        Consumer<String> con1 = (String s) -> {
            System.out.println(s);
        };
        con1.accept("一个是听的人当真了,一个是说的人当真了");
        System.out.println("*********************************");
        Consumer<String> con2 = (s) -> System.out.println(s);
        con2.accept("一个是听的人当真了,一个是说的人当真了");
    
    }
    
    • 语法格式五:Lambda 需要两个或以上的参数,多条执行语句,并且可以有返回值
    @Test
    public void test5() {
        Comparator<Integer> com1 = new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                System.out.println(o1);
                System.out.println(o2);
                return o1.compareTo(o2);
            }
        };
        System.out.println(com1.compare(12, 21));
        System.out.println("*********************************");
        Comparator<Integer> com2 = (o1, o2) -> {
            System.out.println(o1);
            System.out.println(o2);
            return o1.compareTo(o2);
        };
        System.out.println(com2.compare(12, 6));
    }
    
    • 语法格式六:当 Lambda体只有一条语句时, return与大括号若有,都可以省略
    @Test
    public void test6() {
        Comparator<Integer> com1 = (o1, o2) -> {
            return o1.compareTo(o2);
        };
        System.out.println(com1.compare(12, 6));
        System.out.println("*********************************");
        Comparator<Integer> com2 = (o1, o2) ->  o1.compareTo(o2);
        System.out.println(com2.compare(12, 6));
    }
    
    @Test
    public void test7() {
        Consumer<String> con1 = (String s) -> {
            System.out.println(s);
        };
        con1.accept("一个是听的人当真了,一个是说的人当真了");
        System.out.println("*********************************");
        Consumer<String> con2 = s -> System.out.println(s);
        con2.accept("一个是听的人当真了,一个是说的人当真了");
    }
    
    总结:
  • ->左边:lamdba形参列表的参数类型可以省略(类型推断);如果lamdba形参列表只有一个参数,其一对 () 也可以省略。
  • ->右边:lamdba体应该使用一对{}包裹,如果lamdba体只有一条执行语句(可能是return语句),可以省略这一对{}和return关键字
  • lamdba表达式的本质:作为接口的实例

函数式(Functional)接口

  • 只包含一个抽象方法的接口,称为 函数式接口
  • 你可以通过 Lambda 表达式来创建该接口的对象。(若 Lambda 表达式抛出一个受检异常 即:非运行时异常 )),那么该异常需要在目标接口的抽象方法上进行声明)。
  • 我们可以在一个接口上使用 @FunctionalInterface 注解,这样做可以检查它是否是一个函数式接口。同时 javadoc 也会包含一条声明,说明这个接口是一个函数式接口。
  • 在 java.util.function 包下定义 了 Java 8 的丰富的函数式

如何理解函数式接口

  • Java 从诞生日起就是一直倡导“一切皆对象”, 在 Java 里面面向对象 (编程是一切。但是随着 python 、 scala 等语言的兴起和新技术的挑战 Java 不得不做出调整以便支持更加广泛的技术要求,也即 java 不但可以支持 OOP 还可以支持 OOF(面向函数编程)
  • 在函数式编程语言当中,函数被当做一等公民对待。在将函数作为一等公民的编程语言中, Lambda 表达式的类型是函数。但是在 Java8 中,有所不同。在Java8 中, Lambda 表达式是对象,而不是函数,它们必须依附于一类特别的对象类型 函数式接口
  • 简单的说,在 Java8 中, Lambda 表达式就是一个函数式接口的实例。 这就是Lambda 表达式和函数式接口的关系。也就是说,只要一个对象是函数式接口的实例,那么该对象就可以用 Lambda 表达式来表示。
  • 所以以前用 匿名实现类 表示的现在都可以用 Lambda 表达式来写。

函数式 接口举例

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

Java内置四大核心函数式接口

函数式接口参数类型返回类型用途
Consumer< T >
消费型接口
Tvoid对类型为T 的对象应用操作,包含方法:
void accept(T t)
Supplier< T >
供给型接口
T返回类型为T 的对象,包含 方法:
T get()
Function<T, R>
函数型接口
TR对类型为T 的对象应用操作,并返回结果。结果是 R 类型的对象。包含 方法:
R apply(T t)
Predicate< T >
断定型接口
Tboolean确定类型为T 的对象是否满足某约束,并返回boolean 值。包含 方法:
boolean test(T t)

其他接口

在这里插入图片描述

package com.atguigu.Lambda;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;

/**
 * @ClassName LambdaTest2
 * java内置的4大核心函数式接口
 * <p>
 * 消费型接口 Consumer<T>     void accept(T t)
 * 供给型接口 Supplier<T>     T get()
 * 函数型接口 Function<T,R>   R apply(T t)
 * 断定型接口 Predicate<T>    boolean test(T t)
 * @Description
 * @Author wangzhengguo
 * @Date 2020-10-09 13:59:43
 **/
public class LambdaTest2 {

    @Test
    public void test1() {

        happyTime(500, new Consumer<Double>() {
            @Override
            public void accept(Double aDouble) {
                System.out.println("学习太累了,去天上人间买了瓶矿泉水,价格为:" + aDouble);
            }
        });

        System.out.println("********************");

        happyTime(400, money -> System.out.println("学习太累了,去天上人间喝了口水,价格为:" + money));
    }

    public void happyTime(double money, Consumer<Double> con) {
        con.accept(money);
    }


    @Test
    public void test2() {
        List<String> list = Arrays.asList("北京", "南京", "天津", "东京", "西京", "普京");

        List<String> filterStrs = filterString(list, new Predicate<String>() {
            @Override
            public boolean test(String s) {
                return s.contains("京");
            }
        });

        System.out.println(filterStrs);


        List<String> filterStrs1 = filterString(list, s -> s.contains("京"));
        System.out.println(filterStrs1);
    }

    //根据给定的规则,过滤集合中的字符串。此规则由Predicate的方法决定
    public List<String> filterString(List<String> list, Predicate<String> pre) {

        ArrayList<String> filterList = new ArrayList<>();

        for (String s : list) {
            if (pre.test(s)) {
                filterList.add(s);
            }
        }

        return filterList;

    }

}

方法引用与构造器引用

方法引用(Method References)

  • 当 要传递给 Lambda 体的操作,已经有实现的方法了,可以使用方法引用!
  • 方法引用可以看做是 Lambda 表达式深层次的表达。换句话说,方法 引用就是 Lambda 表达式 ,也就是 函数式接口的一个实例,通过方法的名字来指向一个方法,可以认为是 Lambda 表达式的一个语法糖。
  • 要求 实现 接口的抽象方法 的参数列表和返回值类型,必须与方法引用的方法的参数列表和返回值类型保持一致!
  • 格式 使用操作符 " :: "将类 (或对象 ) 与 方法名分隔开来。
  • 如下三种主要使用情况
      对象:: 实例方法名
      类:: 静态方法名
      类:: 实例方法 名
package com.atguigu.MethodReferences;

/**
 * @author shkstart 邮箱:shkstart@126.com
 */
public class Employee {

	private int id;
	private String name;
	private int age;
	private double salary;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public double getSalary() {
		return salary;
	}

	public void setSalary(double salary) {
		this.salary = salary;
	}

	public Employee() {
		System.out.println("Employee().....");
	}

	public Employee(int id) {
		this.id = id;
		System.out.println("Employee(int id).....");
	}

	public Employee(int id, String name) {
		this.id = id;
		this.name = name;
	}

	public Employee(int id, String name, int age, double salary) {

		this.id = id;
		this.name = name;
		this.age = age;
		this.salary = salary;
	}

	@Override
	public String toString() {
		return "Employee{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + ", salary=" + salary + '}';
	}

	@Override
	public boolean equals(Object o) {
		if (this == o)
			return true;
		if (o == null || getClass() != o.getClass())
			return false;

		Employee employee = (Employee) o;

		if (id != employee.id)
			return false;
		if (age != employee.age)
			return false;
		if (Double.compare(employee.salary, salary) != 0)
			return false;
		return name != null ? name.equals(employee.name) : employee.name == null;
	}

	@Override
	public int hashCode() {
		int result;
		long temp;
		result = id;
		result = 31 * result + (name != null ? name.hashCode() : 0);
		result = 31 * result + age;
		temp = Double.doubleToLongBits(salary);
		result = 31 * result + (int) (temp ^ (temp >>> 32));
		return result;
	}
}

package com.atguigu.MethodReferences;

import org.junit.Test;

import java.io.PrintStream;
import java.util.Comparator;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * 方法引用的使用
 *
 * 1.使用情境:当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用!
 *
 * 2.方法引用,本质上就是Lambda表达式,而Lambda表达式作为函数式接口的实例。所以
 *   方法引用,也是函数式接口的实例。
 *
 * 3. 使用格式:  类(或对象) :: 方法名
 *
 * 4. 具体分为如下的三种情况:
 *    情况1     对象 :: 非静态方法
 *    情况2     类 :: 静态方法
 *
 *    情况3     类 :: 非静态方法
 *
 * 5. 方法引用使用的要求:要求接口中的抽象方法的形参列表和返回值类型与方法引用的方法的
 *    形参列表和返回值类型相同!(针对于情况1和情况2)
 *
 * @Author wangzhengguo
 * @Date 2020-10-09 14:15:55
 */

public class MethodRefTest {

	// 情况一:对象 :: 实例方法
	//Consumer中的void accept(T t)
	//PrintStream中的void println(T t)
	@Test
	public void test1() {
		Consumer<String> con1 = str -> System.out.println(str);
		con1.accept("北京");

		System.out.println("*******************");
		PrintStream ps = System.out;
		Consumer<String> con2 = ps::println;
		con2.accept("beijing");
	}
	
	//Supplier中的T get()
	//Employee中的String getName()
	@Test
	public void test2() {
		Employee emp = new Employee(1001,"Tom",23,5600);

		Supplier<String> sup1 = () -> emp.getName();
		System.out.println(sup1.get());

		System.out.println("*******************");
		Supplier<String> sup2 = emp::getName;
		System.out.println(sup2.get());

	}

	// 情况二:类 :: 静态方法
	//Comparator中的int compare(T t1,T t2)
	//Integer中的int compare(T t1,T t2)
	@Test
	public void test3() {
		Comparator<Integer> com1 = (t1,t2) -> Integer.compare(t1,t2);
		System.out.println(com1.compare(12,21));

		System.out.println("*******************");

		Comparator<Integer> com2 = Integer::compare;
		System.out.println(com2.compare(12,3));

	}
	
	//Function中的R apply(T t)
	//Math中的Long round(Double d)
	@Test
	public void test4() {
		Function<Double,Long> func = new Function<Double, Long>() {
			@Override
			public Long apply(Double d) {
				return Math.round(d);
			}
		};

		System.out.println("*******************");

		Function<Double,Long> func1 = d -> Math.round(d);
		System.out.println(func1.apply(12.3));

		System.out.println("*******************");

		Function<Double,Long> func2 = Math::round;
		System.out.println(func2.apply(12.6));
	}

	// 情况三:类 :: 实例方法  (有难度)
	// Comparator中的int comapre(T t1,T t2)
	// String中的int t1.compareTo(t2)
	@Test
	public void test5() {
		Comparator<String> com1 = (s1,s2) -> s1.compareTo(s2);
		System.out.println(com1.compare("abc","abd"));

		System.out.println("*******************");

		Comparator<String> com2 = String :: compareTo;
		System.out.println(com2.compare("abd","abm"));
	}

	//BiPredicate中的boolean test(T t1, T t2);
	//String中的boolean t1.equals(t2)
	@Test
	public void test6() {
		BiPredicate<String,String> pre1 = (s1,s2) -> s1.equals(s2);
		System.out.println(pre1.test("abc","abc"));

		System.out.println("*******************");
		BiPredicate<String,String> pre2 = String :: equals;
		System.out.println(pre2.test("abc","abd"));
	}
	
	// Function中的R apply(T t)
	// Employee中的String getName();
	@Test
	public void test7() {
		Employee employee = new Employee(1001, "Jerry", 23, 6000);


		Function<Employee,String> func1 = e -> e.getName();
		System.out.println(func1.apply(employee));

		System.out.println("*******************");


		Function<Employee,String> func2 = Employee::getName;
		System.out.println(func2.apply(employee));


	}

}

在这里插入图片描述

在这里插入图片描述

构造器引用

在这里插入图片描述

数组引用

在这里插入图片描述

package com.atguigu.MethodReferences;

import org.junit.Test;

import java.util.Arrays;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * 一、构造器引用
 * 和方法引用类似,函数式接口的抽象方法的形参列表和构造器的形参列表一致。
 * 抽象方法的返回值类型即为构造器所属的类的类型
 * <p>
 * 二、数组引用
 * 大家可以把数组看做是一个特殊的类,则写法与构造器引用一致。
 *
 * @Author wangzhengguo
 * @Date 2020-10-09 15:40:06
 */

public class ConstructorRefTest {
    //构造器引用
    //Supplier中的T get()
    //Employee的空参构造器:Employee()
    @Test
    public void test1() {

        Supplier<Employee> sup = new Supplier<Employee>() {
            @Override
            public Employee get() {
                return new Employee();
            }
        };
        System.out.println("*******************");

        Supplier<Employee> sup1 = () -> new Employee();
        System.out.println(sup1.get());

        System.out.println("*******************");

        Supplier<Employee> sup2 = Employee::new;
        System.out.println(sup2.get());
    }

    //Function中的R apply(T t)
    @Test
    public void test2() {
        Function<Integer, Employee> func1 = id -> new Employee(id);
        Employee employee = func1.apply(1001);
        System.out.println(employee);

        System.out.println("*******************");

        Function<Integer, Employee> func2 = Employee::new;
        Employee employee1 = func2.apply(1002);
        System.out.println(employee1);

    }

    //BiFunction中的R apply(T t,U u)
    @Test
    public void test3() {
        BiFunction<Integer, String, Employee> func1 = (id, name) -> new Employee(id, name);
        System.out.println(func1.apply(1001, "Tom"));

        System.out.println("*******************");

        BiFunction<Integer, String, Employee> func2 = Employee::new;
        System.out.println(func2.apply(1002, "Tom"));

    }

    //数组引用
    //Function中的R apply(T t)
    @Test
    public void test4() {
        Function<Integer, String[]> func1 = length -> new String[length];
        String[] arr1 = func1.apply(5);
        System.out.println(Arrays.toString(arr1));

        System.out.println("*******************");

        Function<Integer, String[]> func2 = String[]::new;
        String[] arr2 = func2.apply(10);
        System.out.println(Arrays.toString(arr2));

    }
}

强大的 Stream API

Stream API说明

  • Java8 中有两大最为重要的改变。第一个是 Lambda 表达式 ;另外一个则是 Stream API
  • Stream API ( java.util.stream) 把真正的函数式编程风格引入到 Java 中。这是目前为止对 Java 类库最好的补充,因为 Stream API 可以极大提供 Java 程序员的生产力,让程序员写出高效率、干净、简洁的代码。
  • Stream 是 Java8 中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。 使用
    Stream API 对集合数据进行操作,就类似于使用 SQL 执行的数据库查询。也可以使用 Stream API 来并行执行操作。简言之, Stream API 提供了一种高效且易于使用的处理数据的方式。

为什么要使用Stream API

  • 实际开发中,项目中多数数据源都来自于 Mysql Oracle 等。但现在数据源可以更多了,有 MongDB Radis 等,而这些 NoSQL 的数据就 需要Java 层面去处理 。
  • Stream 和 Collection 集合的区别: Collection 是一种静态的内存数据结构,而 Stream 是有关计算的。 前者是主要面向内存,存储在内存中,后者主要是面向 CPU ,通过 CPU 实现计算。

什么是Stream

  是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列。
  “集合讲的是数据 Stream 讲的是计算!”

注意:

  • Stream 自己不会存储元素。
  • Stream 不会改变源对象。相反,他们会返回一个持有结果的新 Stream 。
  • Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。

Stream的操作三个步骤

  • 1- 创建 Stream:一个数据源(如:集合、数组),获取一个流
  • 2- 中间操作:一个中间操作链,对数据源的数据进行处理
  • 3 终止操作(终端操作):一旦执行 终止操作, 就 执行中间操作链 ,并产生结果 。之后,不会再被使用。
    在这里插入图片描述

创建Stream 方式

package com.atguigu.MethodReferences;

import java.util.ArrayList;
import java.util.List;
/**
 * 提供用于测试的数据
 * 
 * @author shkstart 邮箱:shkstart@126.com
 *
 */
public class EmployeeData {
	
	public static List<Employee> getEmployees(){
		List<Employee> list = new ArrayList<>();
		
		list.add(new Employee(1001, "马化腾", 34, 6000.38));
		list.add(new Employee(1002, "马云", 12, 9876.12));
		list.add(new Employee(1003, "刘强东", 33, 3000.82));
		list.add(new Employee(1004, "雷军", 26, 7657.37));
		list.add(new Employee(1005, "李彦宏", 65, 5555.32));
		list.add(new Employee(1006, "比尔盖茨", 42, 9500.43));
		list.add(new Employee(1007, "任正非", 26, 4333.32));
		list.add(new Employee(1008, "扎克伯格", 35, 2500.32));
		
		return list;
	}
	
}

创建Stream 方式一:通过集合

Java8中的 Collection 接口被扩展,提供了两个获取流
的方法.

  • default Stream stream() : 返回一个顺序流
  • default Stream parallelStream() : 返回一个并行流
创建Stream 方式二:通过数组

Java8中的 Arrays 的静态方法 stream() 可以获取数组流:
static Stream stream(T[] array): 返回一个流
重载形式,能够处理对应基本类型的数组:

  • public static IntStream stream(int[] array)
  • public static LongStream stream(long[] array)
  • public static DoubleStream stream(double[] array)
创建Stream 方式三:通过 Stream 的 of()

可以调用Stream 类静态方法 of(), 通过显示值创建一个
流。它可以接收任意数量的参数。

  • public static Stream of(T… values) : 返回一个流
创建Stream 方式四:创建无限流

可以使用静态方法Stream.iterate() 和 Stream.generate(),创建无限流。
迭代:

  • public static Stream iterate(final T seed, final UnaryOperator f)

生成

  • public static Stream generate(Supplier s)
package com.atguigu.Stream;

import com.atguigu.MethodReferences.Employee;
import com.atguigu.MethodReferences.EmployeeData;
import org.junit.Test;

import java.util.Arrays;
import java.util.EnumMap;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * @author wangzhengguo
 * @Description 测试Stream的实例化
 * @ClassName StreamAPITest
 * @Date 2020/10/9 15:56
 *
 *
 * 1. Stream关注的是对数据的运算,与CPU打交道
 * 集合关注的是数据的存储,与内存打交道
 *
 * 2.
 * ①Stream 自己不会存储元素。
 * ②Stream 不会改变源对象。相反,他们会返回一个持有结果的新Stream。
 * ③Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行
 *
 * 3.Stream 执行流程
 * ① Stream的实例化
 * ② 一系列的中间操作(过滤、映射、...)
 * ③ 终止操作
 *
 * 4.说明:
 * 4.1 一个中间操作链,对数据源的数据进行处理
 * 4.2 一旦执行终止操作,就执行中间操作链,并产生结果。之后,不会再被使用
 */
public class StreamAPITest {
    /**
     * 创建Stream 方式一:通过集合
     */
    @Test
    public void test1() {
        List<Employee> employees = EmployeeData.getEmployees();

        //default Stream<E> stream() : 返回一个顺序流
        Stream<Employee> stream = employees.stream();
        //default Stream<E> parallelStream() : 返回一个并行流
        Stream<Employee> employeeStream = employees.parallelStream();

    }

    /**
     * 创建Stream 方式二:通过数组
     */
    @Test
    public void test2() {
        int[] arr = new int[]{1, 2, 3, 4, 5, 6};
        //调用Arrays类的static <T> Stream<T> stream(T[] array): 返回一个流
        IntStream stream = Arrays.stream(arr);
        Employee e1 = new Employee(1001, "Tom");
        Employee e2 = new Employee(1002, "Jerry");
        Employee[] arr1 = new Employee[]{e1, e2};
        Stream<Employee> stream1 = Arrays.stream(arr1);

    }

    //创建 Stream方式三:通过Stream的of()
    @Test
    public void test3() {

        Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);

    }

    //创建 Stream方式四:创建无限流
    @Test
    public void test4(){

//      迭代
//      public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f)
        //遍历前10个偶数
        Stream.iterate(0, t -> t + 2).limit(10).forEach(System.out::println);


//      生成
//      public static<T> Stream<T> generate(Supplier<T> s)
        Stream.generate(Math::random).limit(10).forEach(System.out::println);

    }
}

Stream的中间操作

  多个中间操作 可以连接起来形成一个 流水线 ,除非流水线上触发终止操作,否则 中间操作不会执行任何的处理 !而在 终止操作时一次性全部处理,称为“惰性求值”

1 筛选与切片

在这里插入图片描述

2 映 射

在这里插入图片描述

3 排序

在这里插入图片描述

package com.atguigu.Stream;

import com.atguigu.MethodReferences.Employee;
import com.atguigu.MethodReferences.EmployeeData;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

/**
 * @ClassName StreamAPITest1
 * @Description 测试Stream的中间操作
 * @Author wangzhengguo
 * @Date 2020/10/9 16:19
 **/
public class StreamAPITest1 {
    /**
     * 1-筛选与切片
     */
    @Test
    public void test1() {
        List<Employee> list = EmployeeData.getEmployees();
//        filter(Predicate p)——接收 Lambda , 从流中排除某些元素。
        Stream<Employee> stream = list.stream();
        //练习:查询员工表中薪资大于7000的员工信息
        stream.filter(employee -> employee.getSalary() > 7000).forEach(System.out::println);

        System.out.println("-----------");
//        limit(n)——截断流,使其元素不超过给定数量。
        list.stream().limit(3).forEach(System.out::println);
        System.out.println("-----------");
//        skip(n) —— 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
        list.stream().skip(3).forEach(System.out::println);
//        distinct()——筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素
        list.add(new Employee(1010, "刘强东", 40, 8000));
        list.add(new Employee(1010, "刘强东", 41, 8000));
        list.add(new Employee(1010, "刘强东", 40, 8000));
        list.add(new Employee(1010, "刘强东", 40, 8000));
        list.add(new Employee(1010, "刘强东", 40, 8000));


        list.stream().distinct().forEach(System.out::println);

    }

    /**
     * 映射
     */
    @Test
    public void test2() {
//        map(Function f)——接收一个函数作为参数,将元素转换成其他形式或提取信息,该函数会被应用到每个元素上,并将其映射成一个新的元素。类似于list的add方法
        List<String> list = Arrays.asList("aa", "bb", "cc", "dd");
        list.stream().map(str -> str.toUpperCase()).forEach(System.out::println);

//        练习1:获取员工姓名长度大于3的员工的姓名。
        List<Employee> employees = EmployeeData.getEmployees();
        Stream<String> namesStream = employees.stream().map(Employee::getName);
        namesStream.filter(name -> name.length() > 3).forEach(System.out::println);
        System.out.println();
        //练习2:
        Stream<Stream<Character>> streamStream = list.stream().map(StreamAPITest1::fromStringToStream);
        streamStream.forEach(s -> {
            s.forEach(System.out::println);
        });
        System.out.println();
//        flatMap(Function f)——接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。类似于list的addAll方法
        Stream<Character> characterStream = list.stream().flatMap(StreamAPITest1::fromStringToStream);
        characterStream.forEach(System.out::println);

    }

    /**
     * 将字符串中的多个字符构成的集合转换为对应的Stream的实例
     *
     * @param str
     * @return
     */
    public static Stream<Character> fromStringToStream(String str) {//aa
        ArrayList<Character> list = new ArrayList<>();
        for (Character c : str.toCharArray()) {
            list.add(c);
        }
        return list.stream();
    }

    @Test
    public void test3() {
        ArrayList list1 = new ArrayList();
        list1.add(1);
        list1.add(2);
        list1.add(3);

        ArrayList list2 = new ArrayList();
        list2.add(4);
        list2.add(5);
        list2.add(6);

//        list1.add(list2);
        list1.addAll(list2);
        System.out.println(list1);

    }

    /**
     * 3-排序
     */
    @Test
    public void test4() {
//        sorted()——自然排序
        List<Integer> list = Arrays.asList(12, 43, 65, 34, 87, 0, -98, 7);
        list.stream().sorted().forEach(System.out::println);
        //抛异常,原因:Employee没有实现Comparable接口
//        List<Employee> employees = EmployeeData.getEmployees();
//        employees.stream().sorted().forEach(System.out::println);


//        sorted(Comparator com)——定制排序

        List<Employee> employees = EmployeeData.getEmployees();
        employees.stream().sorted((e1, e2) -> {

            int ageValue = Integer.compare(e1.getAge(), e2.getAge());
            if (ageValue != 0) {
                return ageValue;
            } else {
                return -Double.compare(e1.getSalary(), e2.getSalary());
            }

        }).forEach(System.out::println);
    }
}

Stream的终止操作

  • 终端操作会从流的流水线生成结果。其结果可以是任何不是流的值,例如: List 、 Integer ,甚至是 void 。
  • 流进行了终止操作后,不能再次使用。
1 匹配与查找

在这里插入图片描述
在这里插入图片描述

2 归约

在这里插入图片描述

3 收集

在这里插入图片描述
  Collector接口中方法的实现决定了如何对流执行收集的操作 如收集到 List 、 Set 、Map) 。
另外,
  另外,Collectors 实用类提供了很多静态方法,可以方便地创建常见收集器实例,具体方法与实例如下表:
在这里插入图片描述
在这里插入图片描述

package com.atguigu.Stream;

import com.atguigu.MethodReferences.Employee;
import com.atguigu.MethodReferences.EmployeeData;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @ClassName StreamAPITest2
 * @Description 测试Stream的终止操作
 * @Author wangzhengguo
 * @Date 2020/10/9 17:21
 **/
public class StreamAPITest2 {
    //1-匹配与查找
    @Test
    public void test1() {
        List<Employee> employees = EmployeeData.getEmployees();

//        allMatch(Predicate p)——检查是否匹配所有元素。
//          练习:是否所有的员工的年龄都大于18
        boolean allMatch = employees.stream().allMatch(e -> e.getAge() > 18);
        System.out.println(allMatch);

//        anyMatch(Predicate p)——检查是否至少匹配一个元素。
//         练习:是否存在员工的工资大于 10000
        boolean anyMatch = employees.stream().anyMatch(e -> e.getSalary() > 10000);
        System.out.println(anyMatch);

//        noneMatch(Predicate p)——检查是否没有匹配的元素。
//          练习:是否存在员工姓“雷”
        boolean noneMatch = employees.stream().noneMatch(e -> e.getName().startsWith("雷"));
        System.out.println(noneMatch);
//        findFirst——返回第一个元素
        Optional<Employee> employee = employees.stream().findFirst();
        System.out.println(employee);
//        findAny——返回当前流中的任意元素
        Optional<Employee> employee1 = employees.parallelStream().findAny();
        System.out.println(employee1);

    }

    @Test
    public void test2() {
        List<Employee> employees = EmployeeData.getEmployees();
        // count——返回流中元素的总个数
        long count = employees.stream().filter(e -> e.getSalary() > 5000).count();
        System.out.println(count);
//        max(Comparator c)——返回流中最大值
//        练习:返回最高的工资:
        Stream<Double> salaryStream = employees.stream().map(e -> e.getSalary());
        Optional<Double> maxSalary = salaryStream.max(Double::compare);
        System.out.println(maxSalary);
//        min(Comparator c)——返回流中最小值
//        练习:返回最低工资的员工
        Optional<Employee> employee = employees.stream().min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
        System.out.println(employee);
        System.out.println();
//        forEach(Consumer c)——内部迭代
        employees.stream().forEach(System.out::println);

        //使用集合的遍历操作
        employees.forEach(System.out::println);
    }

    //2-归约
    @Test
    public void test3() {
//        reduce(T identity, BinaryOperator)——可以将流中元素反复结合起来,得到一个值。返回 T
//        练习1:计算1-10的自然数的和
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        Integer sum = list.stream().reduce(0, Integer::sum);
        System.out.println(sum);


//        reduce(BinaryOperator) ——可以将流中元素反复结合起来,得到一个值。返回 Optional<T>
//        练习2:计算公司所有员工工资的总和
        List<Employee> employees = EmployeeData.getEmployees();
        Stream<Double> salaryStream = employees.stream().map(Employee::getSalary);
//        Optional<Double> sumMoney = salaryStream.reduce(Double::sum);
        Optional<Double> sumMoney = salaryStream.reduce((d1, d2) -> d1 + d2);
        System.out.println(sumMoney.get());

    }

    //3-收集
    @Test
    public void test4() {
//        collect(Collector c)——将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法
//        练习1:查找工资大于6000的员工,结果返回为一个List或Set

        List<Employee> employees = EmployeeData.getEmployees();
        List<Employee> employeeList = employees.stream().filter(e -> e.getSalary() > 6000).collect(Collectors.toList());

        employeeList.forEach(System.out::println);
        System.out.println();
        Set<Employee> employeeSet = employees.stream().filter(e -> e.getSalary() > 6000).collect(Collectors.toSet());

        employeeSet.forEach(System.out::println);

    }
}

并行流与串行流

  并行流就是把一个内容分成多个数据块,并用不同的线程分别处理每个数据块的流 。相比较串行的流, 并行的流可以很大程度上提高程序的执行效率。
  Java 8中将并行进行了优化,我们可以很容易的对数据进行并行操作。Stream API 可以声明性地通过 parallel() 与 sequential() 在并行流与顺序流之间进行切换 。

了解Fork/Join 框架

  Fork/Join 框架:就是在必要的情况下,将一个大任务,进行拆分(fork)成若干个小任务(拆到不可再拆时),再将一个个的小任务运算的结果进行join 汇总.
在这里插入图片描述

Fork/Join 框架与传统线程池的区别

  采用“工作窃取”模式(work-stealing):
  当执行新的任务时它可以将其拆分分成更小的任务执行,并将小任务加到线程队列中,然后再从一个随机线程的队列中偷一个并把它放在自己的队列中。
  相对于一般的线程池实现,fork/join框架的优势体现在对其中包含的任务的处理方式上.在一般的线程池中,如果一个线程正在执行的任务由于某些原因无法继续运行,那么该线程会处于等待状态.而在fork/join框架实现中,如果某个子问题由于等待另外一个子问题的完成而无法继续运行.那么处理该子问题的线程会主动寻找其他尚未运行的子问题来执行.这种方式减少了线程的等待时间,提高了性能.

Optional 类

  1. 到 目前为止,臭名昭著的空指针异常是导致 Java 应用程序失败的最常见原因。以前,为了解决空指针异常, Google 公司著名的 Guava 项目引入了 Optional 类,Guava 通过使用检查空值的方式来防止代码污染,它鼓励程序员写更干净的代码。受到 Google Guava 的启发, Optional 类已经成为 Java 8 类库的一部分。

  2. Optional< T > 类 (java.util.Optional) 是一个容器类 它可以保存类型 T 的值, 代表这个 值存在 。或者仅仅保存 null ,表示这个值 不存在 。原来 用 null 表示一个值不存在,现在 Optional 可以更好的表达这个概念。并且 可以避免空指针异常。

  3. Optional 类的 Javadoc 描述如下:这是一个可以为 null 的容器对象。如果值存在则 isPresent() 方法会返回 true ,调用 get() 方法会返回该对象。

  4. Optional 提供很多有用的方法,这样我们就不用显式进行空值检测。

  5. 创建 Optional 类对象的方法:
    Optional.of(T t) :创建一个 Optional 实例, t 必须非空;
    Optional.empty():创建一个空的 Optional 实例;
    Optional.ofNullable(T t): 可以为 null;

  6. 判断 Optional 容器中是否包含对象:
    boolean isPresent() : 判断是否包含对象;
    void ifPresent(Consumer<? super T> consumer): 如果有值,就执行 Consumer接口的实现代码,并且该值会作为参数传给它。

  7. 获取 Optional 容器的对象:
    T get(): 如果调用对象包含值,返回该值,否则抛异常。
    T orElse(T other): 如果有值则将其返回,否则返回指定的 other 对象。
    T orElseGet(Supplier<? extends T> other) :如果有值则将其返回,否则返回由Supplier 接口实现提供的对象。
    T orElseThrow(Supplier<? extends X> exceptionSupplier) :如果有值则将其返回,否则抛出由 Supplier 接口实现提供的异常 。

测试Optional:

package com.atguigu.Optional;

/**
 * @ClassName Girl
 * @Description
 * @Author wangzhengguo
 * @Date 2020/10/10 10:32
 **/
public class Girl {
    private String name;

    @Override
    public String toString() {
        return "Girl{" + "name='" + name + '\'' + '}';
    }

    public Girl() {
    }

    public Girl(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

package com.atguigu.Optional;

/**
* @ClassName Boy
* @Description
* @Author wangzhengguo
* @Date 2020/10/10 10:32
**/
public class Boy {
   private Girl girl;

   @Override
   public String toString() {
       return "Boy{" + "girl=" + girl + '}';
   }

   public Girl getGirl() {
       return girl;
   }

   public void setGirl(Girl girl) {
       this.girl = girl;
   }

   public Boy() {

   }

   public Boy(Girl girl) {

       this.girl = girl;
   }
}

package com.atguigu.Optional;

import org.junit.Test;

import java.util.Optional;

/**
* @ClassName OptionalTest
* @Description 测试Optional
* @Author wangzhengguo
* @Date 2020/10/10 10:33
*
* Optional类:为了在程序中避免出现空指针异常而创建的。
*
* 常用的方法:ofNullable(T t)
*            orElse(T t)
**/
public class OptionalTest {
   /*
   Optional.of(T t) : 创建一个 Optional 实例,t必须非空;
   Optional.empty() : 创建一个空的 Optional 实例
   Optional.ofNullable(T t):t可以为null

    */

   @Test
   public void test1(){
       Girl girl = new Girl();
//        girl = null;
       //of(T t):保证t是非空的
       Optional<Girl> optionalGirl = Optional.of(girl);

   }
   @Test
   public void test2(){
       Girl girl = new Girl();
//        girl = null;
       //ofNullable(T t):t可以为null
       Optional<Girl> optionalGirl = Optional.ofNullable(girl);
       System.out.println(optionalGirl);
       //orElse(T t1):如果单前的Optional内部封装的t是非空的,则返回内部的t.
       //如果内部的t是空的,则返回orElse()方法中的参数t1.
       Girl girl1 = optionalGirl.orElse(new Girl("赵丽颖"));
       System.out.println(girl1);

   }


   public String getGirlName(Boy boy){
       return boy.getGirl().getName();
   }

   @Test
   public void test3(){
       Boy boy = new Boy();
       boy = null;
       String girlName = getGirlName(boy);
       System.out.println(girlName);

   }

   //优化以后的getGirlName():
   public String getGirlName1(Boy boy){
       if(boy != null){
           Girl girl = boy.getGirl();
           if(girl != null){
               return girl.getName();
           }
       }
       return null;
   }

   @Test
   public void test4(){
       Boy boy = new Boy();
       boy = null;
       String girlName = getGirlName1(boy);
       System.out.println(girlName);

   }

   //使用Optional类的getGirlName():
   public String getGirlName2(Boy boy){

       Optional<Boy> boyOptional = Optional.ofNullable(boy);
       //此时的boy1一定非空
       Boy boy1 = boyOptional.orElse(new Boy(new Girl("迪丽热巴")));

       Girl girl = boy1.getGirl();

       Optional<Girl> girlOptional = Optional.ofNullable(girl);
       //girl1一定非空
       Girl girl1 = girlOptional.orElse(new Girl("古力娜扎"));

       return girl1.getName();
   }

   @Test
   public void test5(){
       Boy boy = null;
       boy = new Boy();
       boy = new Boy(new Girl("苍老师"));
       String girlName = getGirlName2(boy);
       System.out.println(girlName);

   }
}

新时间日期API

传统时间格式化存在线程安全问题

package com.atguigu.Date;

import org.junit.Test;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

/**
* @ClassName TestSimpleDateFormat
* @Description 测试java8时间API
* @Author wangzhengguo
* @Date 2020/10/10 11:01
**/
public class TestSimpleDateFormat {
   @Test
   public void test1() throws Exception {
       SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

       Callable<Date> task = new Callable<Date>() {

   			@Override
   			public Date call() throws Exception {
   				return sdf.parse("20161121");
   			}
   		
   	   };
       ExecutorService pool = Executors.newFixedThreadPool(10);
       List<Future<Date>> results = new ArrayList<>();

       for (int i = 0; i < 10; i++) {
           results.add(pool.submit(task));
       }

       for (Future<Date> future : results) {
           System.out.println(future.get());
       }
   }
}

效果:出现线程安全问题

java.util.concurrent.ExecutionException: java.lang.NumberFormatException: multiple points

	at java.util.concurrent.FutureTask.report(FutureTask.java:122)
	at java.util.concurrent.FutureTask.get(FutureTask.java:192)
	at com.atguigu.Date.TestSimpleDateFormat.test1(TestSimpleDateFormat.java:39)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
	at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
	at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
	at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)
Caused by: java.lang.NumberFormatException: multiple points
	at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1890)
	at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
	at java.lang.Double.parseDouble(Double.java:538)
	at java.text.DigitList.getDouble(DigitList.java:169)
	at java.text.DecimalFormat.parse(DecimalFormat.java:2056)
	at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1867)
	at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)
	at java.text.DateFormat.parse(DateFormat.java:364)
	at com.atguigu.Date.TestSimpleDateFormat$1.call(TestSimpleDateFormat.java:26)
	at com.atguigu.Date.TestSimpleDateFormat$1.call(TestSimpleDateFormat.java:22)
	at java.util.concurrent.FutureTask.run(FutureTask.java:266)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
	at java.lang.Thread.run(Thread.java:745)

解决方法:

  1. java8之前解决方法:新建DateFormatThreadLocal类
package com.atguigu.Date;

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

/**
* @ClassName DateFormatThreadLocal
* @Description java8之前解决日期线程安全问题
* @Author wangzhengguo
* @Date 2020/10/10 11:13
**/
public class DateFormatThreadLocal {
   private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>(){

       protected DateFormat initialValue(){
           return new SimpleDateFormat("yyyyMMdd");
       }

   };

   public static final Date convert(String source) throws ParseException {
       return df.get().parse(source);
   }

}


使用:

 		Callable<Date> task = new Callable<Date>() {
            @Override
            public Date call() throws Exception {
                return DateFormatThreadLocal.convert("20161121");
            }
        };
        ExecutorService pool = Executors.newFixedThreadPool(10);
        List<Future<Date>> results = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            results.add(pool.submit(task));
        }
        for (Future<Date> future : results) {
            System.out.println(future.get());
        }
        pool.shutdown();
  1. 使用ThreadLocal解决线程安全问题:
      DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
      //创建Callable任务
      Callable<LocalDate> task = new Callable<LocalDate>() {
          @Override
          public LocalDate call() throws Exception {
              return LocalDate.parse("20201010",dtf);
          }
      };
      //创建线程池
      ExecutorService pool = Executors.newFixedThreadPool(10);
      List<Future<LocalDate>> results = new ArrayList<>();
      //循环执行任务
      for (int i = 0; i < 10; i++) {
          results.add(pool.submit(task));
      }
      //获取任务结果
      for (Future<LocalDate> future : results) {
          System.out.println(future.get());
      }
      pool.shutdown();

结果:
在这里插入图片描述

使用LocalDate、LocalTime、LocalDateTime

/**
   * 测试LocalDate、LocalTime、LocalDateTime
   */
  @Test
  public void test() {
      //LocalDateTime获取当前时间
      LocalDateTime localDateTime = LocalDateTime.now();
      System.out.println(localDateTime + "\n");

      //LocalDateTime获取指定时间
      LocalDateTime LocalDateTime2 = LocalDateTime.of(2020, 10, 10, 13, 55, 55);
      System.out.println(LocalDateTime2 + "\n");

      //LocalDateTime时间加法运算运算 :plusYears(),plusMonths(),plusDays(),plusHours(),plusMinutes(),plusSeconds()
      LocalDateTime plusYears = localDateTime.plusYears(2);
      System.out.println(plusYears + "\n");//加年


      //LocalDateTime时间减法运算运算:minusYears(),minusMonths(),minusDays(),minusHours(),minusMinutes(),minusSeconds()
      LocalDateTime minusYears = localDateTime.minusYears(2);
      System.out.println(minusYears + "\n");//减年

      //LocalDateTime的get() 获取值
      int year = localDateTime.getYear();
      System.out.println(year);
  }

结果:
在这里插入图片描述
   LocalDate、LocalTime、LocalDateTime 类的实例是不可变的对象,分别表示使用ISO-8601日历系统的日期、时间、日期和时间。它们提供了简单的日期或时间,并不包含当前的时间信息。也不包含与时区相关的信息。
   注:ISO-8601日历系统是国际标准化组织制定的现代公民的日期和时间的表示法
在这里插入图片描述

Instant 时间戳

   用于“时间戳”的运算。它是以Unix元年(传统的设定为UTC时区1970年1月1日午夜时分)开始所经历的描述进行运算。

   /**
    * 2. Instant : 时间戳。 (使用 Unix 元年  1970年1月1日 00:00:00 所经历的毫秒值)
    */
   @Test
   public void test2() {
       //获取当前时间
       Instant ins = Instant.now();  //默认使用 UTC 时区
       System.out.println(ins);

       //获取偏移时间
       OffsetDateTime odt = ins.atOffset(ZoneOffset.ofHours(8));
       System.out.println(odt);

       //获取纳米秒数。
       System.out.println(ins.getNano());

       //使用1970-01-01T00:00:00Z的纪元中的秒来获取Instant的实例。
       Instant ins2 = Instant.ofEpochSecond(60);
       System.out.println(ins2);
   }

结果:
在这里插入图片描述

Duration 和Period

  • Duration:用于计算两个“时间”间隔
  • Period:用于计算两个“日期”间隔
 	/**
     * 3.
     *     Duration : 用于计算两个“时间”间隔
     *     Period : 用于计算两个“日期”间隔
     */
    @Test
    public void test3(){
        Instant ins1 = Instant.now();

        System.out.println("--------------------");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Instant ins2 = Instant.now();

        Duration duration = Duration.between(ins1, ins2);
        System.out.println("所耗费时间为:" + duration.toMillis());

        System.out.println("----------------------------------");

        LocalDate ld1 = LocalDate.now();
        LocalDate ld2 = LocalDate.of(2011, 1, 1);

        Period pe = Period.between(ld2, ld1);
        System.out.println(pe.getYears());
        System.out.println(pe.getMonths());
        System.out.println(pe.getDays());
    }

结果:
在这里插入图片描述

日期的操纵

  • TemporalAdjuster : 时间校正器。有时我们可能需要获取例如:将日期调整到“下个周日”等操作。
  • TemporalAdjusters : 该类通过静态方法提供了大量的常用TemporalAdjuster 的实现。
 	/**
     * 4. TemporalAdjuster : 时间校正器
     */
    @Test
    public void test4(){
        //获取当前时间
        LocalDateTime ldt = LocalDateTime.now();
        System.out.println(ldt);

        //将当前时间的天改为20日
        LocalDateTime ldt2 = ldt.withDayOfMonth(20);
        System.out.println(ldt2);

        //获取下一个周日
        LocalDateTime ldt3 = ldt.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
        System.out.println(ldt3);

        //自定义:下一个工作日
        LocalDateTime ldt5 = ldt.with((l) -> {
            LocalDateTime ldt4 = (LocalDateTime) l;

            DayOfWeek dow = ldt4.getDayOfWeek();

            if(dow.equals(DayOfWeek.FRIDAY)){
                return ldt4.plusDays(3);
            }else if(dow.equals(DayOfWeek.SATURDAY)){
                return ldt4.plusDays(2);
            }else{
                return ldt4.plusDays(1);
            }
        });
        System.out.println(ldt5);
    }
}

解析与格式化

   java.time.format.DateTimeFormatter 类:该类提供了三种格式化方法:

  • 预定义的标准格式
  • 语言环境相关的格式
  • 自定义的格式
 	/**
     * 5. DateTimeFormatter : 解析和格式化日期或时间
     */
    @Test
    public void test5(){
		DateTimeFormatter dtf = DateTimeFormatter.ISO_DATE;
        LocalDateTime ldt = LocalDateTime.now();
        String strDate = ldt.format(dtf);
        //获取年月日
        System.out.println(strDate);

        System.out.println("---------------------------------------------------");

        //格式化当前时间为:yyyy年MM月dd日 HH:mm:ss格式
        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
        String strDate2 = dtf2.format(ldt);
        System.out.println(strDate2);

        //将yyyy年MM月dd日 HH:mm:ss格式转换为2020-10-10T13:57:04格式
        LocalDateTime newDate = ldt.parse(strDate2, dtf2);
        System.out.println(newDate);
    }

结果:

在这里插入图片描述

ZonedDate、ZonedTime、ZonedDateTime : 带时区的时间或日期

在这里插入图片描述
在这里插入图片描述

//获取所有时区信息
Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();
availableZoneIds.forEach(System.out::println);
//结果
Asia/Aden
America/Cuiaba
Etc/GMT+9
Etc/GMT+8
Africa/Nairobi
America/Marigot
Asia/Aqtau
Pacific/Kwajalein
America/El_Salvador
Asia/Pontianak
Africa/Cairo
Pacific/Pago_Pago
Africa/Mbabane
Asia/Kuching
Pacific/Honolulu
Pacific/Rarotonga
America/Guatemala
Australia/Hobart
Europe/London
America/Belize
America/Panama
Asia/Chungking
America/Managua
America/Indiana/Petersburg
Asia/Yerevan
Europe/Brussels
GMT
Europe/Warsaw
America/Chicago
Asia/Kashgar
Chile/Continental
Pacific/Yap
CET
Etc/GMT-1
Etc/GMT-0
Europe/Jersey
America/Tegucigalpa
Etc/GMT-5
Europe/Istanbul
America/Eirunepe
Etc/GMT-4
America/Miquelon
Etc/GMT-3
Europe/Luxembourg
Etc/GMT-2
Etc/GMT-9
America/Argentina/Catamarca
Etc/GMT-8
Etc/GMT-7
Etc/GMT-6
Europe/Zaporozhye
Canada/Yukon
Canada/Atlantic
Atlantic/St_Helena
Australia/Tasmania
Libya
Europe/Guernsey
America/Grand_Turk
US/Pacific-New
Asia/Samarkand
America/Argentina/Cordoba
Asia/Phnom_Penh
Africa/Kigali
Asia/Almaty
US/Alaska
Asia/Dubai
Europe/Isle_of_Man
America/Araguaina
Cuba
Asia/Novosibirsk
America/Argentina/Salta
Etc/GMT+3
Africa/Tunis
Etc/GMT+2
Etc/GMT+1
Pacific/Fakaofo
Africa/Tripoli
Etc/GMT+0
Israel
Africa/Banjul
Etc/GMT+7
Indian/Comoro
Etc/GMT+6
Etc/GMT+5
Etc/GMT+4
Pacific/Port_Moresby
US/Arizona
Antarctica/Syowa
Indian/Reunion
Pacific/Palau
Europe/Kaliningrad
America/Montevideo
Africa/Windhoek
Asia/Karachi
Africa/Mogadishu
Australia/Perth
Brazil/East
Etc/GMT
Asia/Chita
Pacific/Easter
Antarctica/Davis
Antarctica/McMurdo
Asia/Macao
America/Manaus
Africa/Freetown
Europe/Bucharest
Asia/Tomsk
America/Argentina/Mendoza
Asia/Macau
Europe/Malta
Mexico/BajaSur
Pacific/Tahiti
Africa/Asmera
Europe/Busingen
America/Argentina/Rio_Gallegos
Africa/Malabo
Europe/Skopje
America/Catamarca
America/Godthab
Europe/Sarajevo
Australia/ACT
GB-Eire
Africa/Lagos
America/Cordoba
Europe/Rome
Asia/Dacca
Indian/Mauritius
Pacific/Samoa
America/Regina
America/Fort_Wayne
America/Dawson_Creek
Africa/Algiers
Europe/Mariehamn
America/St_Johns
America/St_Thomas
Europe/Zurich
America/Anguilla
Asia/Dili
America/Denver
Africa/Bamako
GB
Mexico/General
Pacific/Wallis
Europe/Gibraltar
Africa/Conakry
Africa/Lubumbashi
Asia/Istanbul
America/Havana
NZ-CHAT
Asia/Choibalsan
America/Porto_Acre
Asia/Omsk
Europe/Vaduz
US/Michigan
Asia/Dhaka
America/Barbados
Europe/Tiraspol
Atlantic/Cape_Verde
Asia/Yekaterinburg
America/Louisville
Pacific/Johnston
Pacific/Chatham
Europe/Ljubljana
America/Sao_Paulo
Asia/Jayapura
America/Curacao
Asia/Dushanbe
America/Guyana
America/Guayaquil
America/Martinique
Portugal
Europe/Berlin
Europe/Moscow
Europe/Chisinau
America/Puerto_Rico
America/Rankin_Inlet
Pacific/Ponape
Europe/Stockholm
Europe/Budapest
America/Argentina/Jujuy
Australia/Eucla
Asia/Shanghai
Universal
Europe/Zagreb
America/Port_of_Spain
Europe/Helsinki
Asia/Beirut
Asia/Tel_Aviv
Pacific/Bougainville
US/Central
Africa/Sao_Tome
Indian/Chagos
America/Cayenne
Asia/Yakutsk
Pacific/Galapagos
Australia/North
Europe/Paris
Africa/Ndjamena
Pacific/Fiji
America/Rainy_River
Indian/Maldives
Australia/Yancowinna
SystemV/AST4
Asia/Oral
America/Yellowknife
Pacific/Enderbury
America/Juneau
Australia/Victoria
America/Indiana/Vevay
Asia/Tashkent
Asia/Jakarta
Africa/Ceuta
Asia/Barnaul
America/Recife
America/Buenos_Aires
America/Noronha
America/Swift_Current
Australia/Adelaide
America/Metlakatla
Africa/Djibouti
America/Paramaribo
Europe/Simferopol
Europe/Sofia
Africa/Nouakchott
Europe/Prague
America/Indiana/Vincennes
Antarctica/Mawson
America/Kralendijk
Antarctica/Troll
Europe/Samara
Indian/Christmas
America/Antigua
Pacific/Gambier
America/Indianapolis
America/Inuvik
America/Iqaluit
Pacific/Funafuti
UTC
Antarctica/Macquarie
Canada/Pacific
America/Moncton
Africa/Gaborone
Pacific/Chuuk
Asia/Pyongyang
America/St_Vincent
Asia/Gaza
Etc/Universal
PST8PDT
Atlantic/Faeroe
Asia/Qyzylorda
Canada/Newfoundland
America/Kentucky/Louisville
America/Yakutat
Asia/Ho_Chi_Minh
Antarctica/Casey
Europe/Copenhagen
Africa/Asmara
Atlantic/Azores
Europe/Vienna
ROK
Pacific/Pitcairn
America/Mazatlan
Australia/Queensland
Pacific/Nauru
Europe/Tirane
Asia/Kolkata
SystemV/MST7
Australia/Canberra
MET
Australia/Broken_Hill
Europe/Riga
America/Dominica
Africa/Abidjan
America/Mendoza
America/Santarem
Kwajalein
America/Asuncion
Asia/Ulan_Bator
NZ
America/Boise
Australia/Currie
EST5EDT
Pacific/Guam
Pacific/Wake
Atlantic/Bermuda
America/Costa_Rica
America/Dawson
Asia/Chongqing
Eire
Europe/Amsterdam
America/Indiana/Knox
America/North_Dakota/Beulah
Africa/Accra
Atlantic/Faroe
Mexico/BajaNorte
America/Maceio
Etc/UCT
Pacific/Apia
GMT0
America/Atka
Pacific/Niue
Canada/East-Saskatchewan
Australia/Lord_Howe
Europe/Dublin
Pacific/Truk
MST7MDT
America/Monterrey
America/Nassau
America/Jamaica
Asia/Bishkek
America/Atikokan
Atlantic/Stanley
Australia/NSW
US/Hawaii
SystemV/CST6
Indian/Mahe
Asia/Aqtobe
America/Sitka
Asia/Vladivostok
Africa/Libreville
Africa/Maputo
Zulu
America/Kentucky/Monticello
Africa/El_Aaiun
Africa/Ouagadougou
America/Coral_Harbour
Pacific/Marquesas
Brazil/West
America/Aruba
America/North_Dakota/Center
America/Cayman
Asia/Ulaanbaatar
Asia/Baghdad
Europe/San_Marino
America/Indiana/Tell_City
America/Tijuana
Pacific/Saipan
SystemV/YST9
Africa/Douala
America/Chihuahua
America/Ojinaga
Asia/Hovd
America/Anchorage
Chile/EasterIsland
America/Halifax
Antarctica/Rothera
America/Indiana/Indianapolis
US/Mountain
Asia/Damascus
America/Argentina/San_Luis
America/Santiago
Asia/Baku
America/Argentina/Ushuaia
Atlantic/Reykjavik
Africa/Brazzaville
Africa/Porto-Novo
America/La_Paz
Antarctica/DumontDUrville
Asia/Taipei
Antarctica/South_Pole
Asia/Manila
Asia/Bangkok
Africa/Dar_es_Salaam
Poland
Atlantic/Madeira
Antarctica/Palmer
America/Thunder_Bay
Africa/Addis_Ababa
Asia/Yangon
Europe/Uzhgorod
Brazil/DeNoronha
Asia/Ashkhabad
Etc/Zulu
America/Indiana/Marengo
America/Creston
America/Mexico_City
Antarctica/Vostok
Asia/Jerusalem
Europe/Andorra
US/Samoa
PRC
Asia/Vientiane
Pacific/Kiritimati
America/Matamoros
America/Blanc-Sablon
Asia/Riyadh
Iceland
Pacific/Pohnpei
Asia/Ujung_Pandang
Atlantic/South_Georgia
Europe/Lisbon
Asia/Harbin
Europe/Oslo
Asia/Novokuznetsk
CST6CDT
Atlantic/Canary
America/Knox_IN
Asia/Kuwait
SystemV/HST10
Pacific/Efate
Africa/Lome
America/Bogota
America/Menominee
America/Adak
Pacific/Norfolk
Europe/Kirov
America/Resolute
Pacific/Tarawa
Africa/Kampala
Asia/Krasnoyarsk
Greenwich
SystemV/EST5
America/Edmonton
Europe/Podgorica
Australia/South
Canada/Central
Africa/Bujumbura
America/Santo_Domingo
US/Eastern
Europe/Minsk
Pacific/Auckland
Africa/Casablanca
America/Glace_Bay
Canada/Eastern
Asia/Qatar
Europe/Kiev
Singapore
Asia/Magadan
SystemV/PST8
America/Port-au-Prince
Europe/Belfast
America/St_Barthelemy
Asia/Ashgabat
Africa/Luanda
America/Nipigon
Atlantic/Jan_Mayen
Brazil/Acre
Asia/Muscat
Asia/Bahrain
Europe/Vilnius
America/Fortaleza
Etc/GMT0
US/East-Indiana
America/Hermosillo
America/Cancun
Africa/Maseru
Pacific/Kosrae
Africa/Kinshasa
Asia/Kathmandu
Asia/Seoul
Australia/Sydney
America/Lima
Australia/LHI
America/St_Lucia
Europe/Madrid
America/Bahia_Banderas
America/Montserrat
Asia/Brunei
America/Santa_Isabel
Canada/Mountain
America/Cambridge_Bay
Asia/Colombo
Australia/West
Indian/Antananarivo
Australia/Brisbane
Indian/Mayotte
US/Indiana-Starke
Asia/Urumqi
US/Aleutian
Europe/Volgograd
America/Lower_Princes
America/Vancouver
Africa/Blantyre
America/Rio_Branco
America/Danmarkshavn
America/Detroit
America/Thule
Africa/Lusaka
Asia/Hong_Kong
Iran
America/Argentina/La_Rioja
Africa/Dakar
SystemV/CST6CDT
America/Tortola
America/Porto_Velho
Asia/Sakhalin
Etc/GMT+10
America/Scoresbysund
Asia/Kamchatka
Asia/Thimbu
Africa/Harare
Etc/GMT+12
Etc/GMT+11
Navajo
America/Nome
Europe/Tallinn
Turkey
Africa/Khartoum
Africa/Johannesburg
Africa/Bangui
Europe/Belgrade
Jamaica
Africa/Bissau
Asia/Tehran
WET
Europe/Astrakhan
Africa/Juba
America/Campo_Grande
America/Belem
Etc/Greenwich
Asia/Saigon
America/Ensenada
Pacific/Midway
America/Jujuy
Africa/Timbuktu
America/Bahia
America/Goose_Bay
America/Virgin
America/Pangnirtung
Asia/Katmandu
America/Phoenix
Africa/Niamey
America/Whitehorse
Pacific/Noumea
Asia/Tbilisi
America/Montreal
Asia/Makassar
America/Argentina/San_Juan
Hongkong
UCT
Asia/Nicosia
America/Indiana/Winamac
SystemV/MST7MDT
America/Argentina/ComodRivadavia
America/Boa_Vista
America/Grenada
Australia/Darwin
Asia/Khandyga
Asia/Kuala_Lumpur
Asia/Famagusta
Asia/Thimphu
Asia/Rangoon
Europe/Bratislava
Asia/Calcutta
America/Argentina/Tucuman
Asia/Kabul
Indian/Cocos
Japan
Pacific/Tongatapu
America/New_York
Etc/GMT-12
Etc/GMT-11
Etc/GMT-10
SystemV/YST9YDT
Europe/Ulyanovsk
Etc/GMT-14
Etc/GMT-13
W-SU
America/Merida
EET
America/Rosario
Canada/Saskatchewan
America/St_Kitts
Arctic/Longyearbyen
America/Fort_Nelson
America/Caracas
America/Guadeloupe
Asia/Hebron
Indian/Kerguelen
SystemV/PST8PDT
Africa/Monrovia
Asia/Ust-Nera
Egypt
Asia/Srednekolymsk
America/North_Dakota/New_Salem
Asia/Anadyr
Australia/Melbourne
Asia/Irkutsk
America/Shiprock
America/Winnipeg
Europe/Vatican
Asia/Amman
Etc/UTC
SystemV/AST4ADT
Asia/Tokyo
America/Toronto
Asia/Singapore
Australia/Lindeman
America/Los_Angeles
SystemV/EST5EDT
Pacific/Majuro
America/Argentina/Buenos_Aires
Europe/Nicosia
Pacific/Guadalcanal
Europe/Athens
US/Pacific
Europe/Monaco
 	/**
     * 6.ZonedDate、ZonedTime、ZonedDateTime : 带时区的时间或日期
     */
    @Test
    public void test7(){
        //获取所有时区信息
//        Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();
//        availableZoneIds.forEach(System.out::println);

        //带时区的的时间
        LocalDateTime ldt = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
        System.out.println(ldt);
        
        ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("US/Pacific"));
        System.out.println(zdt);
    }

显示:
在这里插入图片描述

  • 8
    点赞
  • 42
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

java水泥工

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值