Day28JavaSE——JDK1.8新特性

Day28JavaSE——JDK1.8新特性

Lambda表达式
stream流
日期时间API

Lambda表达式

概述

Lambda 是一个匿名函数,我们可以把 Lambda表达式理解为是一段可以传递的代码(将代码像数据一样进行传递)。可以写出更简洁、更灵活的代码。作为一种更紧凑的代码风格,使Java的语言表达能力得到了提升。
//Lambda表达式的语法
        //JDK1.8 引入了一个箭头符号 ->
        //这个箭头符号 将Lambda表达式分为 左右两部分。 左边->右边
        // 左边:写的是你实现的这个接口中的抽象方法的 形参列表
        // 右边:写的是你对接口中这个抽象方法的具体实现逻辑。
        //如果我要得到一个MyInterface的子类对象,那我们可以使用匿名内部类来得到该接口的一个子类对象。
public class Test1 {
    public static void main(String[] args) {
        //Lambda表达式:JDK1.8引入的一种语法,这种语法可以对匿名内部类的写法进行简化
        ArrayList<Integer> list = new ArrayList<>();
        list.add(20);
        list.add(0);
        list.add(30);
        list.add(11);
        list.add(65);
        //Comparator 比较器 一个接口
        list.sort(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                //实现逻辑,最核心的代码
                return o1-o2;
            }
        });
        System.out.println(list);

        System.out.println("==================");
        //使用Lambda表达式,对以上的代码进行简化
        list.sort((o1,o2)->o2-o1);
        System.out.println(list);
    }
}
public class Test2 {
    public static void main(String[] args) {
        System.out.println("==========方式1==========");
        //方式1:我们就采用匿名内部类的方式
        MyInterface myInterface = new MyInterface() {
            @Override
            public void show(int a, int b) {
                System.out.println(a + b);
                System.out.println(b - a);
            }
        };

        System.out.println("==========方式2==========");
        //方式2:采用Lambda表达式,对匿名内部类进行简写
        //第一步简写。抽象方法的参数列表->具体的实现逻辑
        MyInterface myInterface1 = (int a, int b) -> {
            System.out.println(a + b);
            System.out.println(b - a);
        };

        //第二步简写:可以省略形参列表的参数数据类型
        MyInterface myInterface2 = (a, b) -> {
            System.out.println(a + b);
            System.out.println(b - a);
        };
        //第三步简写:我们对抽象方法的实现逻辑,只有一行代码那么方法体的大括号可以省略不写
    }
}
通过上面的对比,发现Lambda表达式式书写起来更为简洁
那我们具体来看一下Lambda表达式的书写语法
Lambda 表达式在Java 语言中引入了一个新的语法元素和操作符。这个操作符为 “ ->” , 该操作符被称为 Lambda 操作符或箭头操作符。它将 Lambda 分为两个部分:
左侧: 指定了 Lambda 表达式需要的所有参数
右侧: 指定了 Lambda 体,即 Lambda 表达式要执行的功能。

Lambda表达式注意事项

public class Test1 {
    public static void main(String[] args) {
        //1、采用匿名内部类
        MyInterface m1 = new MyInterface() {
            @Override
            public int test(int a, int b) {
                return a + b;
            }
        };
        //2、使用Lambda表达式简写
        MyInterface m2 = (a,b)->a+b;
        //你对方法的实现逻辑,只有一行那么{} 和return 关键字都可以省略不写
        //你对方法的实现逻辑,不止一行,那么这个{}和return 就不能省略
        MyInterface m3 = (a,b)->{
            int c=a+b;
            return c;
        };
    }
}
public class Test2 {
    public static void main(String[] args) {
        MyInterface2 myInterface2 = new MyInterface2() {
            @Override
            public int show(int a) {
                return a+100;
            }
        };

        //简写
        //如果形参只有一个参数,那么数据类型和()括号都可以省略不写
        MyInterface2 myInterface3 = a->a+100;
    }
}
上述 Lambda 表达式中的参数类型都是由编译器推断得出的。 Lambda 表达式中无需指定类型,程序依然可以编译,这是因为 javac 根据程序的上下文,在后台推断出了参数的类型。 Lambda 表达式的类型依赖于上下文环境,是由编译器推断出来的。这就是所谓的“类型推断”.
public class Test1 {
    public static void main(String[] args) {
        //匿名内部类可以作为参数进行传递,Lambda表达式也可以作为参数传递
        Integer[] arr={10,34,4};
        Comparator<Integer> comparator = new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1-o2;
            }
        };
        Arrays.sort(arr,comparator);
        System.out.println(Arrays.toString(arr));
        System.out.println("==========================");
        //简写
        //直接把,Lambda表达式传递来
        Arrays.sort(arr,(a,b)->a-b);
        System.out.println(Arrays.toString(arr));
    }
}
public class Test2 {
    public static void main(String[] args) {
        Integer[] arr = {20, 3, 144};
        //你可以先写成匿名内部类。然后你按alt+enter一提示,可以让IDEA给你转换成Lambda表达式
        Arrays.sort(arr, (a, b) -> a - b);

        System.out.println(arr);
    }
}

Lambda表达式的限制

//Lambda表达式的使用限制:Lambda表达式,需要函数式接口的支持。
        //函数式接口:这个接口中,只有一个抽象方法,这种接口我们就称之为函数式接口。
        //有一个注解 @FunctionalInterface 可以检测这个接口是不是一个函数式接口
public class Test1 {
    public static void main(String[] args) {
        //匿名内部类
        MyInterface myInterface = new MyInterface() {
            @Override
            public void h() {
                System.out.println("hhhhhhhhhhhhhh");
            }
            @Override
            public void d() {
                System.out.println("ddddddddddddddd");
            }
        };
        //如果一个接口中,有很多抽象方法,那么Lambda表达式,就无法写出来。那么就只能用匿名内部类。
    }
}
public class Test2 {
    public static void main(String[] args) {
        //JDK1.8之后,他提供了很多的函数式接口。来作为参数传递。
        Consumer consumer = new Consumer() {
            @Override
            public void accept(Object o) {
                System.out.println(o);
            }
        };
        //简写
        Consumer consumer1 = o->System.out.println(o);
    }
}

Java中提供的4大核心函数式接口

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

其他函数式接口

函数式接口参数类型返回类型用途
BiFunction<T,U,R>T UR对类型为 T, U 参数应用
操作, 返回 R 类型的结
果。 包含方法为
R apply(T t, U u);
UnaryOperator(Function的子接口)TT对类型为T的对象进行一 元运算, 并返回T类型的 结果。 包含方法为 T apply(T t);
BinaryOperator(BiFunction的子接口)T TT对类型为T的对象进行二
元运算, 并返回T类型的
结果。 包含方法为
T apply(T t1, T t2);
BiConsumer<T,U>T Uvoid对类型为T, U 参数应用
操作。 包含方法为
void accept(T t, U u)
ToIntFunction ToLongFunction ToDoubleFunctionTint long double分 别 计 算 int 、 long 、
double、 值的函数
IntFunction LongFunction DoubleFunctionint
long
double
R参数分别为int、 long、
double 类型的函数

方法引用与构造器引用

我们先来看一下什么是方法引用:方法引用其实是Lambda表达式的另一种写法,
当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用.
注意:实现抽象方法的参数列表,必须与方法引用方法的参数列表保持一致!
方法引用:使用操作符 “ ::” 将方法名和对象或类的名字分隔开来。
如下三种主要使用情况:
 对象::实例方法
 类::静态方法
 类::实例方法
方法引用
public class Test1 {
    public static void main(String[] args) {
        //方法引用是对Lambda表达式的进一步简写
        Consumer<String> consumer = new Consumer<String>() {
            @Override
            public void accept(String o) {
                //具体实现逻辑
                //此写法是下面写法的链式编程System.out.println(o);
                PrintStream out = System.out;
                out.println(o);
            }
        };
        consumer.accept("hello");

        System.out.println("===================");
        //对上面代码进行第一次简写
        Consumer<String> consumer2 = o-> System.out.println(o);
        consumer2.accept("ggggggggggg");

        System.out.println("===================");
        //对上面的Lambda表达式还能再次简写。
        //方法引用:对接口中的抽象方法 public void accept(String s) 的具体实现逻辑,是不是就是  System.out.println(x);
        //注意观察接口中的抽象方法 accept(String s) 这个抽象方法 返回值是void 然后有一个参数。
        //再观察你对这个抽象方法的具体实现,System.out.println(x); 的实现逻辑,用了一个对象 PrintStream
        //然后这个PrintStream 调用了一个println(x)这个方法,那么println(x)方法你观察发现,这个方法返回值也是void 然后也是一个参数。
        //那么println(x)方法的返回值和参数列表 正好跟重写的这个accept(String s)方法的返回值和参数列表一致
        //那么就可以使用方法引用进行简写
        //语法就是 对象::实例方方法
        //对上面代码进行第二次简写
        Consumer<String> consumer3 = System.out::println;
        consumer3.accept("gfasfgasgas");
    }
}
public class Test2 {
    public static void main(String[] args) {
        BinaryOperator<Double> doubleBinaryOperator = new BinaryOperator<Double>(){

            @Override
            public Double apply(Double a, Double b) {
                double max = Math.max(a, b);
                return max;
            }
        };

        System.out.println("=====================");
        BinaryOperator<Double> doubleBinaryOperator2 = (a,b)->Math.max(a,b);

        System.out.println("=====================");
        BinaryOperator<Double> doubleBinaryOperator3 = Math::max;
        Double max = doubleBinaryOperator3.apply(5.5, 7.08);
        System.out.println(max);
    }
}
public class Test3 {
    public static void main(String[] args) {
        // Predicate<T> 断言型接口
        Predicate<String> predicate = new Predicate<String>() {
            @Override
            public boolean test(String s) {
                return s.equals("2");
            }
        };
        System.out.println("======================");
        Predicate<String> predicate2 = s->s.equals("2");
        System.out.println(predicate2.test("3"));
        System.out.println(predicate2.test("2"));
    }
}
public class Test4 {
    public static void main(String[] args) {
        Comparator<Integer> comparator = new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return Integer.compare(o1, o2);
            }
        };
        System.out.println("============================");
        Comparator<Integer> comparator1 = (a, b) -> Integer.compare(a, b);

        System.out.println("============================");
        Comparator<Integer> comparator2 = Integer::compare;
        System.out.println(comparator2.compare(7, 5));
    }
}
public class Test5 {
    public static void main(String[] args) {
        Comparator<String> comparator = new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        };

        System.out.println("===========================");
        //简写
        Comparator<String> comparator1 = (a,b)->a.compareTo(b);
        System.out.println(comparator1.compare("s", "t"));

        System.out.println("===========================");
        //方法引用: 类名::实例方法
        //我们重写接口中的方法,传入的两个参数。一个参数作为了调用者,一个参数作为了传入者。
        Comparator<String> comparator2 = String::compareTo;
        System.out.println(comparator2.compare("aaa", "aaa"));

        System.out.println("===========================");
        Comparator<String> comparator3 = new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.indexOf(o2);
            }
        };

        System.out.println("===========================");
        Comparator<String> comparator4 = (o1, o2) -> o1.indexOf(o2);
        //方法引用: 类名::实例方法
        Comparator<String> comparator5 = String::indexOf;

        ArrayList<String> list = new ArrayList<String>();
        list.add("abc");
        list.add("ccbc");
        list.add("eeec");
        list.add("fffc");
        list.add("dddbc");
        list.add("jj");
        list.add("wwwabc");
        list.sort(String::compareTo);
        for (String s : list) {
            System.out.println(s);
        }
    }
}
构造引用
格式:ClassName::new
与函数式接口相结合,自动与函数式接口中方法兼容。可以把构造器引用赋值给定义的方法,与构造器参数列表要与接口中抽象方法的参数列表一致!
public class Test1 {
    public static void main(String[] args) {
        Supplier<Student> supplier = new Supplier<Student>() {
            @Override
            public Student get() {
                Student student = new Student();
                return student;
            }
        };
        Student student = supplier.get();
        System.out.println(student);
        System.out.println("=====================");
        Supplier<Student> supplier1 = () ->new Student();
        System.out.println("=============================");
        //还能简写:构造引用
        //我对抽象方法get() 的重写逻辑是 用new 调用了一个空参构造方法   Student()
        //这个空参构造方法 Student() 没有参数,而且new完之后,会返回一个对象了
        //正好跟 get() 方法的 参数列表和返回值类型能对应上,那么就可以使用构造引用

        //构造引用
        Supplier<Student> supplier3=Student::new;
    }
}
public class Test2 {
    public static void main(String[] args) {
        //具体的 实现逻辑
        //Student zhangsan = new Student("zhangsan", 23);
        //找一个函数式接口,这个接口中的抽象方法、要两个参数 这个方法还得有返回值。
        //BiFunction<T, U, R> T是方法的第一个形参类型,U是方法的第二个形参类型 R是方法的返回 值类型
        BiFunction<String, Integer, Student> biFunction = new BiFunction<String, Integer, Student>() {

            @Override
            public Student apply(String name, Integer age) {
                //Student student = new Student("zhangsan", 23);
                return new Student(name, age);
            }
        };
        // Student sudent = biFunction.apply("王五", 26);

        //第一步简化:
        BiFunction<String, Integer, Student> biFunction2 = (name, age) -> new Student(name, age);

        //使用构造引用进行简化

        BiFunction<String, Integer, Student> biFunction3 = Student::new;

        Supplier<Student> supplier = Student::new;
    }
}

stream流

Stream API

*Stream 是 Java8 中处理集合的关键抽象概念,
	它可以指定你希望对集合进行的操作,
	可以执行非常复杂的查找、过滤和映射数据等操作。
	使用Stream API 对集合数据进行操作,就类似于使用 SQL 执行的数据库查询。也可以使用 Stream API 来并行执行操作。
	简而言之,Stream API 提供了一种高效且易于使用的处理数据的方式。
*流(Stream) 到底是什么呢?
	是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列。
	集合讲的是数据,流讲的是计算!
	*注意:
	①Stream 自己不会存储元素。
	②Stream 不会改变源对象。相反,他们会返回一个持有结果的新Stream。
	③Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。

Stream 的操作三个步骤

1.创建 Stream
	一个数据源(如:集合、数组),获取一个流
2.中间操作
	一个中间操作链,对数据源的数据进行处理
3.终止操作(终端操作)
	一个终止操作,执行中间操作链,并产生结果
public class Test {
    public static void main(String[] args) {
        /*使用Stream流分三个阶段
        * 1、获取Stream流
        * 2、进行中间环节的操作
        * 3、终止操作*/

        //1、获取Stream流的方式
        //先有一个容器
        System.out.println("==============方式1==============");
        List<Integer> list = Arrays.asList(20, 30, 44, 898, 546, 787, 4);
        //通过集合中的方法stream()来获取一个Stream()流
        Stream<Integer> stream = list.stream();

        System.out.println("==============方式2==============");
        //获取一个Stream流 Arrays.stream(arr);
        Integer[] arr={50,60,80,6,4};
        Stream<Integer> stream1 = Arrays.stream(arr);

        System.out.println("==============方式3==============");
        //通过Stream这个类中的静态方法of()
        Stream<Integer> stream2 = Stream.of(5, 6, 8, 2, 4, 6);
        Stream<List<Integer>> list1 = Stream.of(list);
        Stream<Integer> arr1 = Stream.of(arr);

        System.out.println("==============方式4==============");
        //获取无限流
        Stream<Integer> iterate = Stream.iterate(1, num -> num + 1);

        //中间操作
        Stream<Integer> limit = iterate.limit(5);

        //终止操作
        limit.forEach(integer -> System.out.println(integer));

        //limit.forEach(num-> System.out.println(num));
        //方法引用:对象::实例方法
        //limit.forEach(System.out::println);

        System.out.println("==============方式5==============");
        Stream<Double> generate = Stream.generate(() -> {
            double random = Math.random();
            return random;
        });
        //中间操作
        Stream<Double> limit1 = generate.limit(10);

        //终止操作
        limit1.forEach(System.out::println);
    }
}
public class Test1 {
    public static void main(String[] args) {
        //使用Stream流分三个步骤
        //1.获取一个Stream流,来关联一个容器。
        //2.进行中间环节的操作,来得到一个持有新结果的流
        //3.进行终止操作,来得到我们的结果,但是不会对原有的容器有任何改变。
        //1、构建一个容器
        List<Employee> list = Arrays.asList(new Employee(102, "adair", 55, 66666),
                new Employee(101, "张三", 18, 9999.99),
                new Employee(103, "王五", 28, 3333.33),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(105, "田七", 38, 5555.55)
        );

        //2、获取流
        //3、中间操作
        //4、终止操作
        //filter(Predicate p) 过滤 接收 Lambda ,从流中排除某些元素。

        list.stream().filter(employee -> employee.getSalary()>6000).forEach(System.out::println);
        System.out.println("====================================");

        //过滤出姓赵的员工
        //获取流.中间操作.终止操作
        list.stream().filter(employee -> employee.getName().startsWith("赵")).forEach(System.out::println);
        System.out.println("====================================");
        //流对集合的操作结果是新建一个集合将结果存放进去,原集合不受影响
        System.out.println(list);
    }
}
public class Test2 {
    public static void main(String[] args) {
        //filter(Predicate p) 过滤 接收 Lambda ,从流中排除某些元素。
        // distinct() 去重,需要元素 重写hashCode()和equals()方法
        List<Employee> list = Arrays.asList(new Employee(102, "adair", 55, 66666),
                new Employee(101, "张三", 18, 9999.99),
                new Employee(103, "王五", 28, 3333.33),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(105, "田七", 38, 5555.55)
        );
        //流持有容器中的数据---->过滤中间操作(返回一个持有新结果的流)--->中间操作过滤(返回一个持有新结果的流)--->终止操作(遍历持有新结果的流)
        list.stream().filter(employee -> employee.getSalary()>6000).distinct().forEach(System.out::println);
    }
}
public class Employee {
    private int id;
    private String name;
    private int age;
    private double salary;//工资

    private Status status;//状态

    public Employee(){}

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

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

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

    public Employee(int id, String name, int age, double salary, Status status) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.salary = salary;
        this.status = status;
    }

    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 Status getStatus() {
        return status;
    }

    public void setStatus(Status status) {
        this.status = status;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employee employee = (Employee) o;
        return id == employee.id &&
                age == employee.age &&
                Double.compare(employee.salary, salary) == 0 &&
                Objects.equals(name, employee.name) &&
                status == employee.status;
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name, age, salary, status);
    }

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

    //枚举
    public enum Status{
        FREE,
        BUSY,
        VOCATION;
    }
}

创建Stream的方式

1.Java8 中的 Collection 接口被扩展,提供了
	  两个获取流的方法:
		default Stream<E> stream() : 返回一个顺序流
		default Stream<E> parallelStream() : 返回一个并行流 
	2.Java8 中的 Arrays 的静态方法 stream() 可以获取数组流:
		static <T> Stream<T> stream(T[] array): 返回一个流
		 重载形式,能够处理对应基本类型的数组:
		 public static IntStream stream(int[] array)
		 public static LongStream stream(long[] array)
		 public static DoubleStream stream(double[] array) 
	3.由值创建流,可以使用静态方法 Stream.of(), 通过显示值创建一个流。它可以接收任意数量的参数。
		 public static<T> Stream<T> of(T... values) : 返回一个流 
	4.由函数创建流:创建无限流可以使用静态方法 Stream.iterate()和Stream.generate(), 创建无限流。
		public static<T> Stream<T> iterate(final T seed, finalUnaryOperator<T> f)  迭代
		public static<T> Stream<T> generate(Supplier<T> s)  生成

Stream 的中间操作

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

	1.筛选与切片
		filter(Predicate p) 过滤 接收 Lambda , 从流中排除某些元素。
		distinct() 去重,通过流所生成元素的 hashCode() 和 equals() 去除重复元素
		limit(long maxSize) 截断流,使其元素不超过给定数量。
		skip(long n)	    跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
	2.映射
		map(Function f)			接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
		flatMap(Function f)		接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流.
		mapToDouble(ToDoubleFunction f)	接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 DoubleStream。
		mapToInt(ToIntFunction f)	接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 IntStream。
		mapToLong(ToLongFunction f)	接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 LongStream。
		
         3.排序
		sorted()	产生一个新流,其中按自然顺序排序   元素实现Compareble接口
		sorted(Comparator comp)	产生一个新流,其中按比较器顺序排序  传入一个比较
public class Test1 {
    public static void main(String[] args) {
         /*  limit( long maxSize)截断流,使其元素不超过给定数量。
        skip( long n)跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit (n) 互补*/
        List<Integer> list = Arrays.asList(20, 30, 55, 99, 34);
        Stream<Integer> stream = list.stream();
        //获取大于10的元素并从头截断3个
        stream.filter(num->num>20).limit(3).forEach(System.out::println);

        System.out.println("======================");
        //容器有了
        List<Employee> list2 = Arrays.asList(
                new Employee(102, "李四", 59, 6666.66),
                new Employee(101, "张三", 18, 9999.99),
                new Employee(103, "王五", 28, 3333.33),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(105, "田七", 38, 5555.55)
        );
        //获取年龄大于20的员工
        list2.stream().filter(employee -> employee.getAge()>20).limit(1).forEach(System.out::println);
    }
}
public class Test2 {
    public static void main(String[] args) {
        //skip(2) 跳过前两个不要,取后面剩下的,跟limit()互补
        List<Integer> list = Arrays.asList(20, 30, 55, 99, 34);
        Stream<Integer> stream = list.stream();
        Stream<Integer> integerStream = stream.filter(num -> {
            System.out.println("中间环节执行了");
            return num > 20;
        });
        //在这里要注意,当终止操作没有执行时,中间环节不执行,体现了延迟加载的思想,用的时候再加载执行
        integerStream.forEach(System.out::println);
    }
}
public class Test1 {
    public static void main(String[] args) {
        System.out.println("=================案例1=================");
        List<String> list = Arrays.asList("aaa", "bbb", "ccc", "ddd");
        //把集合中的元素变大写
        Stream<String> stream = list.stream();
        //map:提取集合中的元素,应用到一个方法上
        stream.map(s->s.toUpperCase()).forEach(System.out::print);
        System.out.println();

        System.out.println("=================案例2=================");
        List<String> list2 = Arrays.asList("aaa", "bbb", "ccc", "ddd");
        Stream<String> stream2 = list2.stream();
        //提取集合中的每一个元素,把这个字符串,截取成一个个字符,放到换一个集合中,在把这个集合转换成Stream流返回。
        Stream<Stream<Character>> streamStream = stream2.map(new Function<String, Stream<Character>>() {
            @Override
            public Stream<Character> apply(String s) {
                // 提取集合中的每一个元素,把这个字符串,截取成一个个字符,放到一个集合中,在把这个集合转换成Stream流返回。
                //这个操作,没有现成方法可用,那自己就编写一个
                return getStreamChar(s);
            }
        });

        //终止操作
        streamStream.forEach(new Consumer<Stream<Character>>() {
            @Override
            public void accept(Stream<Character> characterStream) {
                characterStream.forEach(character -> System.out.print(character));
            }
        });
        System.out.println();

        System.out.println("=================案例3=================");
        //flatMap(Function f)接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流.
        //用flatMap 来做一下
        List<String> list3 = Arrays.asList("aaa", "bbb", "ccc", "ddd");
        Stream<String> stream3 = list2.stream();
        Stream<Character> characterStream = stream3.flatMap(new Function<String, Stream<Character>>() {
            @Override
            public Stream<Character> apply(String s) {
                return getStreamChar(s);
            }
        });
        characterStream.forEach(character -> System.out.print(character));
        System.out.println();

        System.out.println("=================案例4=================");
        //输出列表元素的平方
        List<Integer> list4 = Arrays.asList(2, 5, 7, 9);
        list4.stream().mapToInt(value -> (int)Math.pow(value,2)).forEach(value -> System.out.println(value));

        System.out.println("=================案例5=================");
        //按年龄大小排序
        List<Employee> list5 = Arrays.asList(new Employee(102, "adair", 55, 66666),
                new Employee(101, "张三", 18, 9999.99),
                new Employee(103, "王五", 28, 3333.33),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(105, "田七", 38, 5555.55)
        );
        //自然排序要求元素实现一个Compareble接口
        //stream.sorted()
        //使用比较器排序
        list5.stream().sorted((o1,o2)-> o1.getAge() - o2.getAge()).forEach(System.out::println);
    }
    private static Stream<Character> getStreamChar(String s) {
        ArrayList<Character> arrayList = new ArrayList<>();
        for (char c : s.toCharArray()) {
            arrayList.add(c);
        }
        Stream<Character> stream = arrayList.stream();
        return stream;
    }
}

Stream 的终止操作

终端操作会从流的流水线生成结果。其结果可以是任何不是流的值,例如:List、Integer,甚至是 void 。

	1.查找与匹配
		allMatch(Predicate p)	检查是否匹配所有元素  比如判断 所有员工的年龄都是17岁 如果有一个不是,就返回false
		anyMatch(Predicate p)	检查是否至少匹配一个元素  比如判断是否有姓王的员工,如果至少有一个就返回true
		noneMatch(Predicate p)	检查是否没有匹配所有元素  employee.getSalary() < 3000; 每个员工的工资如果都高于3000就返回true 如果有一个低于3000 就返回false
		findFirst()		返回第一个元素  比如获取工资最高的人  或者 获取工资最高的值是
		findAny()		返回当前流中的任意元素   比如随便获取一个姓王的员工
		count()	返回流中元素总数  
		max(Comparator c)	返回流中最大值  比如:获取最大年龄值
		min(Comparator c)	返回流中最小值  比如:获取最小年龄的值
		forEach(Consumer c)	内部迭代(使用 Collection 接口需要用户去做迭代,称为外部迭代。相反,Stream API 使用内部迭代——它帮你把迭代做了)
	2.归约
		reduce(T iden, BinaryOperator b)  参1 是起始值, 参2 二元运算	可以将流中元素反复结合起来,得到一个值。返回 T  比如: 求集合中元素的累加总和 
		reduce(BinaryOperator b) 这个方法没有起始值	可以将流中元素反复结合起来,得到一个值。返回 Optional<T>  , 比如你可以算所有员工工资的总和
		备注:map 和 reduce 的连接通常称为 map-reduce 模式,因 Google 用它来进行网络搜索而出名。
	3.收集
		collect(Collector c)	将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法
		Collector 接口中方法的实现决定了如何对流执行收集操作(如收集到 List、Set、Map)。
		但是 Collectors 实用类提供了很多静态方法,可以方便地创建常见收集器实例,具体方法与实例如下
	 4.Collectors 中的方法
		List<T> toList()		把流中元素收集到List   比如把所有员工的名字通过map()方法提取出来之后,在放到List集合中去
			例子:List<Employee> emps= list.stream().map(提取名字).collect(Collectors.toList());
		Set<T>  toSet()		把流中元素收集到Set  比如把所有员工的名字通过map()方法提取出来之后,在放到Set集合中去
			例子:Set<Employee> emps= list.stream().collect(Collectors.toSet());
		Collection<T> toCollection()		把流中元素收集到创建的集合 比如把所有员工的名字通过map()方法提取出来之后,在放到自己指定的集合中去
			例子:Collection<Employee>emps=list.stream().map(提取名字).collect(Collectors.toCollection(ArrayList::new));
		Long counting()		计算流中元素的个数
			例子:long count = list.stream().collect(Collectors.counting());
		Integer	summingInt()	对流中元素的整数属性求和
			例子:inttotal=list.stream().collect(Collectors.summingInt(Employee::getSalary));
		Double averagingInt()		计算流中元素Integer属性的平均值
			例子:doubleavg= list.stream().collect(Collectors.averagingInt(Employee::getSalary));
		IntSummaryStatistics summarizingInt()	收集流中Integer属性的统计值。
			例子:DoubleSummaryStatistics dss= list.stream().collect(Collectors.summarizingDouble(Employee::getSalary));
			   从DoubleSummaryStatistics 中可以获取最大值,平均值等
                                                   	double average = dss.getAverage();
        				long count = dss.getCount();
      			                double max = dss.getMax();
		String joining() 连接流中每个字符串  比如把所有人的名字提取出来,在通过"-"横杠拼接起来
			例子:String str= list.stream().map(Employee::getName).collect(Collectors.joining("-"));
		Optional<T> maxBy() 根据比较器选择最大值  比如求最大工资
			例子:Optional<Emp>max= list.stream().collect(Collectors.maxBy(comparingInt(Employee::getSalary)));
		Optional<T> minBy() 根据比较器选择最小值  比如求最小工资
			例子:Optional<Emp> min = list.stream().collect(Collectors.minBy(comparingInt(Employee::getSalary)));
		归约产生的类型 reducing() 从一个作为累加器的初始值开始,利用BinaryOperator与流中元素逐个结合,从而归约成单个值
			例子:inttotal=list.stream().collect(Collectors.reducing(0, Employee::getSalar, Integer::sum));
		转换函数返回的类型 collectingAndThen()		包裹另一个收集器,对其结果转换函数
			例子:inthow= list.stream().collect(Collectors.collectingAndThen(Collectors.toList(), List::size));
		Map<K, List<T>> groupingBy() 根据某属性值对流分组,属性为K,结果为V  比如按照 状态分组
			例子:Map<Emp.Status, List<Emp>> map= list.stream().collect(Collectors.groupingBy(Employee::getStatus));
		Map<Boolean, List<T>> partitioningBy() 根据true或false进行分区 比如 工资大于等于6000的一个区,小于6000的一个区
			例子:Map<Boolean,List<Emp>>vd= list.stream().collect(Collectors.partitioningBy(Employee::getSalary));


public class Test1 {
    public static void main(String[] args) {
        //终止操作,当我们执行完了中间环节,就想要执行终止操作,来得到中间环节流持有的结果
        //终止操作中,最常用的一个操作,就是遍历,forEach();
        //有的时候,并不是只想打印看,我们是想要获取中间环节操作完之后的结果。
        // allMatch(Predicate p) 检查是否匹配所有元素 比如判断 所有员工的年龄都是17岁 如果有一个不是, 就返回false
        List<Employee> list = Arrays.asList(
                new Employee(102, "李四", 59, 6666.66),
                new Employee(101, "张三", 18, 9999.99),
                new Employee(103, "王五", 28, 3333.33),
                new Employee(104, "赵六", 17, 7777.77),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(104, "赵六", 17, 7777.77),
                new Employee(105, "田七", 38, 5555.55)
        );

        Stream<Employee> stream = list.stream();

        System.out.println("===================================");
        //终止操作
        boolean b = stream.allMatch(new Predicate<Employee>() {
            @Override
            public boolean test(Employee employee) {
                return employee.getAge() == 18;
            }
        });
        System.out.println(b);

        System.out.println("===================================");
        //中间操作:把所有年龄取出来
        Stream<Employee> stream1 = list.stream();
        boolean b1 = stream1.map(new Function<Employee, Integer>() {
            @Override
            public Integer apply(Employee employee) {
                return employee.getAge();
            }
        }).allMatch(new Predicate<Integer>() {
            @Override
            public boolean test(Integer integer) {
                return integer == 18;
            }
        });

        System.out.println(b1);
    }
}
public class Test2 {
    public static void main(String[] args) {
        //判断他们的工资有没有人高于7000 只有一个人高于7000 都返回true
        // anyMatch(Predicate p) 检查是否至少匹配一个元素 比如判断是否有姓王的员工, 如果至少有一个就返回true
        List<Employee> list = Arrays.asList(
                new Employee(102, "李四", 59, 6666.66),
                new Employee(101, "张三", 18, 9999.99),
                new Employee(103, "王五", 28, 3333.33),
                new Employee(104, "赵六", 17, 7777.77),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(104, "赵六", 17, 7777.77),
                new Employee(105, "田七", 38, 5555.55)
        );
        boolean b = list.stream().anyMatch(new Predicate<Employee>() {
            @Override
            public boolean test(Employee employee) {
                return employee.getSalary() > 7000;
            }
        });
        System.out.println(b);
    }
}
public class Test3 {
    public static void main(String[] args) {
        //  noneMatch(Predicate p) 检查是否没有匹配所有元素
        List<Employee> list = Arrays.asList(
                new Employee(102, "李四", 59, 6666.66),
                new Employee(101, "张三", 18, 9999.99),
                new Employee(103, "王五", 28, 3333.33),
                new Employee(104, "赵六", 17, 7777.77),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(104, "赵六", 17, 7777.77),
                new Employee(105, "田七", 38, 5555.55)
        );
        System.out.println(list.stream().noneMatch(employee -> employee.getSalary() < 4000));
    }
}
public class Test1 {
    public static void main(String[] args) {
        List<Employee> list = Arrays.asList(
                new Employee(102, "李四", 59, 6666.66),
                new Employee(101, "张三", 18, 9999.99),
                new Employee(103, "王五", 28, 3333.33),
                new Employee(104, "赵六", 17, 7777.77),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(104, "赵六", 17, 7777.77),
                new Employee(105, "田七", 38, 0.55)
        );
        // findFirst() 返回第一个元素 比如获取工资最高的人 或者 获取工资最高的值是
        // Optional 容器,会把员工放到这个容器中
        //取得最高工资9999.99
        Optional<Employee> first = list.stream().sorted(((o1, o2) -> Double.compare(o2.getSalary(), o1.getSalary()))).findFirst();
        Employee employee = first.get();
        System.out.println(employee);
        System.out.println("====================================");
        //方式2
        Optional<Double> first1 = list.stream().map(employee1 -> employee1.getSalary()).sorted((a, b) -> (int) (b - a)).findFirst();
        Double aDouble = first1.get();
        System.out.println(aDouble);
    }
}
public class Test2 {
    public static void main(String[] args) {
        //findAny() 返回当前流中的任意元素 比如随便获取一个姓王的员工
        List<Employee> list = Arrays.asList(
                new Employee(102, "李四", 59, 6666.66),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(103, "王五", 28, 3333.33),
                new Employee(104, "王六", 17, 7777.77),
                new Employee(104, "王六", 17, 7777.77),
                new Employee(104, "王六", 17, 7777.77),
                new Employee(104, "王六", 17, 7777.77),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(104, "赵六", 17, 7777.77),
                new Employee(105, "田七", 38, 0.55)
        );
        //串行流list.stream()
        //并行流:list.parallelStream()
        System.out.println(list.parallelStream().filter(new Predicate<Employee>() {
            @Override
            public boolean test(Employee employee) {
                return employee.getName().startsWith("王");
            }
        }).findAny().get());

        System.out.println("=======================");
        //count()统计流中的元素格式
        System.out.println(list.stream().distinct().count());

        System.out.println("=======================");
        System.out.println(list.stream().min(new Comparator<Employee>() {
            @Override
            public int compare(Employee o1, Employee o2) {
                return (int) (o1.getSalary() - o2.getSalary());
            }
        }).get());

        System.out.println("=======================");
        System.out.println(list.stream().map(e -> e.getSalary()).min(new Comparator<Double>() {
            @Override
            public int compare(Double o1, Double o2) {
                return (int) (o1 - o2);
            }
        }).get());
    }
}
public class Test3 {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(20, 30, 50, 200);
        /*  reduce(T iden, BinaryOperator b) 参1 是起始值, 参2 二元运算 可以将流中元素反复结合起来,得到一个值。返回 T 比如:
        求集合中元素的累加总和*/
        System.out.println(list.stream().reduce((a, b) -> a + b).get());

        System.out.println("=================================");
        //参数1:你可以给一个起始值
        System.out.println(list.stream().reduce(0, (a, b) -> a + b));

        System.out.println("=================================");
        List<Employee> list2 = Arrays.asList(
                new Employee(102, "李四", 59, 6666.66),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(103, "王五", 28, 3333.33),
                new Employee(104, "王六", 17, 7777.77),
                new Employee(104, "王六", 17, 7777.77),
                new Employee(104, "王六", 17, 7777.77),
                new Employee(104, "王六", 17, 7777.77),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(104, "赵六", 17, 7777.77),
                new Employee(105, "田七", 38, 0.55)
        );

        //求员工工资总和
        System.out.println(list2.stream().map(employee -> employee.getSalary()).reduce(0.0, (a, b) -> a + b));
    }
}
public class Test1 {
    public static void main(String[] args) {
        //收集流中的结果
        List<Employee> list = Arrays.asList(
                new Employee(102, "李四", 59, 6666.66),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(103, "王五", 28, 3333.33),
                new Employee(104, "王六", 17, 7777.77),
                new Employee(104, "王六", 17, 7777.77),
                new Employee(104, "王六", 17, 7777.77),
                new Employee(104, "王六", 17, 7777.77),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(104, "赵六", 17, 7777.77),
                new Employee(105, "田七", 38, 0.55)
        );
        //把结果收集到List集合
        System.out.println(list.stream().map(e -> e.getName()).distinct().collect(Collectors.toList()));
        //把结果收集到Set集合
        System.out.println(list.stream().map(e -> e.getName()).distinct().collect(Collectors.toSet()));
        //收集到指定集合里面
        list.stream().map(e->e.getName()).distinct().collect(Collectors.toCollection(LinkedHashSet::new));
        //平均工资
        System.out.println(list.stream().collect(Collectors.averagingDouble(e -> e.getSalary())));
        System.out.println("======================================");
        //将名字取出来拼串的两种方式
        System.out.println(list.stream().map(Employee::getName).collect(Collectors.joining("-")));
        System.out.println(list.stream().map(Employee::getName).collect(Collectors.joining(",", "[", "]")));
    }
}
public class Test2 {
    public static void main(String[] args) {
        //请平均工资,求总工资,求最高工资,最低工资
        List<Employee> list= Arrays.asList(
                new Employee(102, "李四", 59, 6666.66),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(103, "王五", 28, 3333.33),
                new Employee(104, "王六", 17, 7777.77),
                new Employee(104, "王六", 17, 7777.77),
                new Employee(104, "王六", 17, 7777.77),
                new Employee(104, "王六", 17, 7777.77),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(104, "赵六", 17, 7777.77),
                new Employee(105, "田七", 38, 0.55)
        );
        DoubleSummaryStatistics collect = list.stream().collect(Collectors.summarizingDouble(Employee::getSalary));
        double max = collect.getMax();
        double min = collect.getMin();
        double average = collect.getAverage();
        double sum = collect.getSum();
        long count = collect.getCount();

        System.out.println(max);
        System.out.println(min);
        System.out.println(average);
        System.out.println(sum);
        System.out.println(count);

        System.out.println("========================");
        Optional<Employee> collect1 = list.stream().collect(Collectors.maxBy((e1, e2) -> (int) (e1.getSalary() - e2.getSalary())));
        Employee employee = collect1.get();
        System.out.println(employee);

        Optional<Double> collect2 = list.stream().map(Employee::getSalary).collect(Collectors.minBy((a, b) -> (int) (a - b)));
        System.out.println(collect2.get());
    }
}

并行流与串行流

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

日期时间API

LocalDate、 LocalTime、 LocalDateTime类的实例是不可变的对象,
分别表示使用 ISO-8601日历系统的日期、时间、日期和时间。
它们提供了简单的日期或时间,并不包含当前的时间信息。也不包含与时区相关的信息。
注: ISO-8601日历系统是国际标准化组织制定的现代公民的日期和时间的表示法
这些新增的日期时间API都在 java.time包下

获取对象的方法

方式1通过静态方法  now();
		例如:LocalDateTime ldt = LocalDateTime.now();

	方式2通过静态方法of()方法参数可以指定年月日时分秒
		例如:LocalDateTime of = LocalDateTime.of(2018, 12, 30, 20, 20, 20);
public class Test1 {
    public static void main(String[] args) {
        //JDK1.8 新增加的一些好用的 内容
        //新增了一套新的时间日期API
        //Lambda表达式
        //Stream

        // Date
        //  SimpleDateFormat
        //  Calendar
        // LocalDate  表示年月日
        // LocalTime  时分秒
        // LocalDateTime 年月日 时分秒
        //获取当年的年月日时分秒
        System.out.println(LocalDate.now());
        System.out.println(LocalTime.now());
        System.out.println(LocalDateTime.now());

        System.out.println("============================");
        //指定年月日,时分秒
        LocalDateTime.of(2010,10,10,13,30,30);
        LocalDate.of(2019,03,05);
        LocalTime.of(14,30,30);
    }
}
public class Test2 {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now);
        //获取年月日时分秒
        //有关于获取的方法 getXXX()
        int year = now.getYear();
        //获取月份 JUNE
        Month month = now.getMonth(); //返回的枚举类型
        //获取月份 6 ISO-8601日历系统 从1数月份
        int monthValue = now.getMonthValue(); //返回数字的月份
        int dayOfMonth = now.getDayOfMonth();
        //获取星期,返回的是枚举类型
        DayOfWeek dayOfWeek = now.getDayOfWeek();
        int dayOfYear = now.getDayOfYear();
        int hour = now.getHour();
        int minute = now.getMinute();
        int second = now.getSecond();

        System.out.println(year);
        System.out.println(month);
        System.out.println(monthValue);
        System.out.println(dayOfMonth);
        System.out.println(dayOfWeek);
        System.out.println(dayOfYear);
        System.out.println(hour);
        System.out.println(minute);
        System.out.println(second);
    }
}
public class Test3 {
    public static void main(String[] args) {
        //格式化日期
        LocalDate now = LocalDate.now();
        System.out.println(now);
        //DateTimeFormatter JDK1.8提供的格式化日期的类
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        //format()格式化日期的方法,需要你传入的格式化对象
        String format = now.format(dateTimeFormatter);
        System.out.println(format);

        System.out.println("============================");
        LocalTime now1 = LocalTime.now();
        System.out.println(now1);
        DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("HH时mm分ss秒");
        String format1 = now1.format(dateTimeFormatter2);
        System.out.println(format1);

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

        LocalDateTime now2 = LocalDateTime.now();
        DateTimeFormatter dateTimeFormatter3 = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒");
        System.out.println(now2);
        String format2 = now2.format(dateTimeFormatter3);
        System.out.println(format2);
    }
}
public class Test4 {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now);
        //转成年月日的这个类
        LocalDate localDate = now.toLocalDate();
        System.out.println(localDate);
        //转成时分秒这个类
        LocalTime localTime = now.toLocalTime();
        System.out.println(localTime);
    }
}

常用方法

1.与获取相关的方法:get系类的方法
		ldt.getYear();获取年
		ldt.getMinute();获取分钟
		ldt.getHour();获取小时
		getDayOfMonth 获得月份天数(1-31)
		getDayOfYear 获得年份天数(1-366)
		getDayOfWeek 获得星期几(返回一个 DayOfWeek枚举值)
		getMonth 获得月份, 返回一个 Month 枚举值
		getMonthValue 获得月份(1-12)
		getYear 获得年份
	2.格式化日期日期字符串的方法 format()
		例如:String yyyy = ldt.format(DateTimeFormatter.ofPattern("yyyy"));
	3.转换的方法 toLocalDate();toLocalTime();
		例如:LocalDate localDate = ldt.toLocalDate();
		例如:LocalTime localTime = ldt.toLocalTime();
	4.判断的方法
		isAfter()判断一个日期是否在指定日期之后
		isBefore()判断一个日期是否在指定日期之前
		isEqual(); 判断两个日期是否相同
		isLeapYear()判断是否是闰年注意是LocalDate类中的方法
			例如:  boolean after = ldt.isAfter(LocalDateTime.of(2024, 1, 1, 2, 3));
			例如  boolean b= LocalDate.now().isLeapYear();

	5.解析的静态方法parse("2007-12-03T10:15:30");
		paser() 将一个日期字符串解析成日期对象,注意字符串日期的写法的格式要正确,否则解析失败
			例如:LocalDateTime parse = LocalDateTime.parse("2007-12-03T10:15:30");

		按照我们指定的格式去解析:
		
		注意细节:如果用LocalDateTime 想按照我们的自定义的格式去解析,注意
		日期字符串的 年月日时分秒要写全,不然就报错
			LocalDateTime ldt4 = LocalDateTime.now();
			DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
			LocalDateTime.parse("2018-01-21 20:30:36", formatter2);

	6.添加年月日时分秒的方法 plus系列的方法 都会返回一个新的LocalDateTime的对象
		LocalDateTime localDateTime = ldt.plusYears(1);
		LocalDateTime localDateTime1 = ldt.plusMonths(3);
		LocalDateTime localDateTime2=ldt.plusHours(10);
	7.减去年月日时分秒的方法 minus 系列的方法 注意都会返回一个新的LocalDateTime的对象
		例如:LocalDateTime localDateTime2 = ldt.minusYears(8);
	8.指定年月日时分秒的方法 with系列的方法 注意都会返回一个新的LocalDateTime的对象
		例如 LocalDateTime localDateTime3 = ldt.withYear(1998);
		  //获取这个月的第几个星期几是几号,比如 TemporalAdjusters.dayOfWeekInMonth(2, DayOfWeek.FRIDAY) 代表的意思是这个月的第二个星期五是几号
 			  // TemporalAdjusters.dayOfWeekInMonth(2, DayOfWeek.FRIDAY)
  			  LocalDateTime with1 = now.with(TemporalAdjusters.dayOfWeekInMonth(2,DayOfWeek.FRIDAY));
public class Test1 {
    public static void main(String[] args) {
        LocalDate now = LocalDate.now();
        LocalDate of = LocalDate.of(2018, 2, 3);
        //判断一个日期在不在另一个日期之后
        boolean b = now.isAfter(of);
        System.out.println(b);
        //判断一个日期在不在另一个日期之前
        boolean before = of.isBefore(now);
        System.out.println(before);
        //判断两个日期是否相同
        boolean equal = now.isEqual(of);
        System.out.println(equal);
        //判断一个年份是不是闰年
        boolean leapYear = of.isLeapYear();
        System.out.println(leapYear);
    }
}
public class Test2 {
    public static void main(String[] args) {
        //解析日期:把日期字符串转换成日期对象
        //按照默认格式去解析的
        String str = "2020-11-11";
        LocalDate parse = LocalDate.parse(str);
        System.out.println(parse);

        System.out.println("============================");
        //按照默认格式去解析
        String time = "20:10:10";
        LocalTime parse1 = LocalTime.parse(time);
        System.out.println(parse1);

        System.out.println("============================");
        //按照默认格式去解析的 默认格式 2020-10-10T20:30:30
        String s="2020-10-10T20:30:30";
        LocalDateTime parse2 = LocalDateTime.parse(s);
        System.out.println(parse2);

        LocalDateTime now = LocalDateTime.now();
        System.out.println(now);

        System.out.println("============================");
        //按照指定格式解析
        String str2 = "2020年10月10日";
        //指定格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        LocalDate parse22 = LocalDate.parse(str2, formatter);
        System.out.println(parse22);

        System.out.println("============================");
        String ss = "2020-10-10 20:30:30";
        DateTimeFormatter formatter33 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime parse3 = LocalDateTime.parse(ss, formatter33);
        System.out.println(parse3);
    }
}
public class Test3 {
    public static void main(String[] args) {
        //给日期增加时间量的方法
        LocalDateTime now = LocalDateTime.now();

        //plusXXX系列的方法,增加完时间量后,会返回一个新的对象
        LocalDateTime localDateTime = now.plusYears(1);
        System.out.println(localDateTime);
        LocalDateTime localDateTime1 = now.plusMonths(2);
        System.out.println(localDateTime1);
        System.out.println("==========================");
        //给日期减去相应的时间量 minusXXX 系列方法,调用完毕返回一个新的日期对象
        LocalDateTime now1 = LocalDateTime.now();
        LocalDateTime localDateTime2 = now1.minusYears(2);
        System.out.println(localDateTime2);

        LocalDateTime localDateTime3 = now1.minusDays(10);
        System.out.println(localDateTime3);
    }
}
public class Test {
    public static void main(String[] args) {
        LocalDate now = LocalDate.now();
        //withXXX方法,指定日期,调用完,返回的是一个新的日期对象。
        LocalDate localDate = now.withYear(2015);
        System.out.println(localDate);
        System.out.println(now.withMonth(10));
        System.out.println(now.withDayOfMonth(20));

        System.out.println("======================================");
        LocalDate now1 = LocalDate.now();
        //TemporalAdjuster 接口
        TemporalAdjuster next = TemporalAdjusters.next(DayOfWeek.MONDAY);
        LocalDate with = now1.with(next);
        System.out.println(with);

        System.out.println("======================================");
        TemporalAdjuster temporalAdjuster = TemporalAdjusters.firstInMonth(DayOfWeek.FRIDAY);
        LocalDate with1 = now1.with(temporalAdjuster);
        System.out.println(with1);
        System.out.println("==================================");
        TemporalAdjuster temporalAdjuster1 = TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY);
        LocalDate with2 = now1.with(temporalAdjuster1);
        System.out.println(with2);

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

        TemporalAdjuster temporalAdjuster2 = TemporalAdjusters.firstDayOfNextMonth();
        LocalDate with3 = now1.with(temporalAdjuster2);
        System.out.println(with3);
        //dayOfWeekInMonth(4, DayOfWeek.FRIDAY); 本月的第四个星期五
        TemporalAdjuster temporalAdjuster3 = TemporalAdjusters.dayOfWeekInMonth(4, DayOfWeek.FRIDAY);
        LocalDate with4 = now1.with(temporalAdjuster3);
        System.out.println(with4);
    }
}

Instant 时间戳类从1970-01-01 00:00:00 截止到当前时间的毫秒值

1获取对象的方法 now()
	注意默认获取出来的是当前的美国时间和我们相差八个小时
		Instant ins = Instant.now();
		System.out.println(ins);
		我们在东八区 所以可以加8个小时 就是我们的北京时间
2. Instant中设置偏移量的方法:atOffset() 设置偏移量
		OffsetDateTime time = ins.atOffset(ZoneOffset.ofHours(8));
		System.out.println(time);
3.获取系统默认时区时间的方法atZone()
	方法的参数是要一个时区的编号可以通过时区编号类获取出来
		ZoneId.systemDefault()获取本地的默认时区ID
		ZonedDateTime zonedDateTime = ins.atZone(ZoneId.systemDefault());
		System.out.println(zonedDateTime);
4.get系列的方法

	getEpochSecond() 获取从1970-01-01 00:00:00到当前时间的秒值
	toEpochMilli();获取从1970-01-01 00:00:00到当前时间的毫秒值
	getNano()方法是把获取到的当前时间的秒数 换算成纳秒
	long epochSecond = ins.getEpochSecond();//获取从1970-01-01 00:00:00到当前时间的秒值
	getNano()方法是把获取到的当前时间的豪秒数 换算成纳秒 比如当前时间是2018-01-01 14:00:20:30
	那就把30豪秒换算成纳秒 int nano = ins.getNano();
5. ofEpochSecond()方法 给计算机元年增加秒数
	ofEpochMilli() 给计算机元年增加毫秒数
	例如 Instant instant = Instant.ofEpochSecond(5);
		 System.out.println(instant);
		单位换算
		 0.1 毫秒 = 105次方纳秒 = 100000 纳秒
   			 1 毫秒 = 1000 微妙 = 1000000 纳秒
public class Test1 {
    public static void main(String[] args) {
        long l = System.currentTimeMillis();
        //Instant 时间戳类从1970 -01 - 01 00:00:00 截止到当前时间的毫秒值
        //获取 Instant 对象 now()
        Instant now = Instant.now();
        System.out.println(now);

        //获取毫秒值
        long l1 = now.toEpochMilli();
        System.out.println(l);
        System.out.println(l1 / 1000);

        //获取间隔的秒值 getEpochSecond()
        long epochSecond = now.getEpochSecond();
        System.out.println(now.toEpochMilli() / 1000);
    }
}
public class Test2 {
    public static void main(String[] args) {
        Instant now = Instant.now();
        System.out.println(now);
        //now.atOffset(ZoneOffset.ofHours(8)); 偏移8个小时 得到一个偏移的时间 OffsetDateTime
        OffsetDateTime offsetDateTime = now.atOffset(ZoneOffset.ofHours(8));
        System.out.println(offsetDateTime);
    }
}
public class Test3 {
    public static void main(String[] args) {
        //  ZoneId 时间时区类
        //systemDefault(); 获取系统默认的时区变化
        ZoneId zoneId = ZoneId.systemDefault();
        //Asia / Shanghai
        System.out.println(zoneId);
        System.out.println("===========================");
        //获取世界所有的时区编号
        Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();
        for (String availableZoneId : availableZoneIds) {
            System.out.println(availableZoneId);
        }
        // America/Bogota
        ZoneId id = ZoneId.of("America/Bogota");
        //获取某个时区的日期
        LocalDateTime now = LocalDateTime.now(id);
        System.out.println(now);

        //使用的就是系统默认的时区
        LocalDateTime now1 = LocalDateTime.now();
        System.out.println(now1);

        LocalDateTime now2 = LocalDateTime.now(ZoneId.systemDefault());
        System.out.println(now2);


        System.out.println("===========================");
        //ofEpochSecond() 方法 给计算机元年增加秒数
        //ofEpochMilli() 给计算机元年增加毫秒数

    /*    Date date = new Date(1000 * 60 * 60);
        System.out.println(date);*/
        Instant instant = Instant.ofEpochMilli(1000 * 60 * 60);
        System.out.println(instant);
        Instant instant1 = Instant.ofEpochSecond(60 * 60 * 24);
        System.out.println(instant1);
    }
}

Duration : 用于计算两个“时间”间隔的类

Period : 用于计算两个“日期”间隔的类

Duration类中静态方法between()
	Instant start = Instant.now();
		for(int i=0;i<1000L;i++){
			System.out.println("循环内容");
		}
	Instant end = Instant.now();
	静态方法:between() 计算两个时间的间隔,默认是秒
	Duration between = Durati’on.between(start, end);
	Duration中的toMillis()方法:将秒转成毫秒
	System.out.println(between.toMillis());

Period类 中的静态方法between()
	计算两个日期之间的间隔
	LocalDate s = LocalDate.of(1985, 03, 05);
	LocalDate now = LocalDate.now();
	Period be = Period.between(s, now);
	System.out.println(be.getYears());间隔了多少年
	System.out.println(be.getMonths());间隔了多少月
	System.out.println(be.getDays());间隔多少天
public class Test2 {
    public static void main(String[] args) {
        LocalDate birthday = LocalDate.of(1985, 3, 5);
        LocalDate now = LocalDate.now();
        // Period:用于计算两个“日期”间隔的类
        Period between = Period.between(birthday, now);
        int years = between.getYears();
        int months = between.getMonths();
        int days = between.getDays();
        System.out.println(years);
        System.out.println(months);
        System.out.println(days);
    }
}

TemporalAdjuster : 时间校正器,是个接口

一般我们用该接口的一个对应的工具类 TemporalAdjusters中的一些常量,来指定日期
例如:
LocalDate now = LocalDate.now();
    System.out.println(now);
1 使用TemporalAdjusters自带的常量来设置日期
	LocalDate with = now.with(TemporalAdjusters.lastDayOfYear());
	System.out.println(with);
2 采用TemporalAdjusters中的next方法来指定日期
	 LocalDate date = now.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
	 System.out.println(date);
	例如:TemporalAdjusters.next(DayOfWeek.SUNDAY) 本周的星期天
	例如:TemporalAdjusters.nextOrSame(DayOfWeek.MONDAY) 下一周的星期一
3 采用自定义的方式来指定日期 比如指定下个工作日
	 LocalDateTime ldt = LocalDateTime.now();
	LocalDateTime workDay = ldt.with(new TemporalAdjuster() {
		@Override
	 public Temporal adjustInto(Temporal temporal) {
		 //向下转型
		 LocalDateTime ld = (LocalDateTime) temporal;
		 //获取这周的星期几
		 DayOfWeek dayOfWeek = ld.getDayOfWeek();
	 if (dayOfWeek.equals(DayOfWeek.FRIDAY)) {
			 return ld.plusDays(3);//如果这天是星期五,那下个工做日就加3天
		} else if (dayOfWeek.equals(DayOfWeek.SATURDAY)) {
			return ld.plusDays(2);//如果这天是星期六,那下个工做日就加2天
		} else {
			//其他就加一天
			return ld.plusDays(1);
	 }
        }
    });

    System.out.println(workDay);
public class Test1 {
    public static void main(String[] args) {
        //public interface TemporalAdjuster 时间矫正器 是个接口
        //调用 TemporalAdjusters 这个工具类中的一些方法,就可以得到TemporalAdjuster接口子类对象
        LocalDate now = LocalDate.now();
        TemporalAdjuster temporalAdjuster = TemporalAdjusters.lastDayOfMonth();
        TemporalAdjuster temporalAdjuster1 = TemporalAdjusters.lastDayOfYear();
        LocalDate with = now.with(temporalAdjuster1);
        System.out.println(with);

        //对于一些常用的日子  这个工具类中TemporalAdjusters 有相应的方法。
        //对于一些特殊的日子,可能这个工具类中没有相应的方法提供
        //比如我想知道下一个工作日是几号?
        System.out.println("==============================");
        LocalDate now2 = LocalDate.now();
        LocalDate with1 = now2.with(new TemporalAdjuster() {
            @Override
            //参数 temporal 当前的日期
            public Temporal adjustInto(Temporal temporal) {
                //如果这天是星期五。下个工作日,是当前时间加3天
                //如果是星期6,下个工作日是当前时间加2天
                //其余星期加1天
                //向下转型
                LocalDate localDate = (LocalDate) temporal;
                //获取今天是星期几
                DayOfWeek dayOfWeek = localDate.getDayOfWeek();
                if (dayOfWeek.equals(DayOfWeek.FRIDAY)) {
                    LocalDate localDate1 = localDate.plusDays(3);
                    return localDate1;
                } else if (dayOfWeek.equals(DayOfWeek.SATURDAY)) {
                    LocalDate localDate2 = localDate.plusDays(2);
                    return localDate2;
                } else {
                    LocalDate localDate3 = localDate.plusDays(1);
                    return localDate3;
                }
            }
        });
        System.out.println(with1);
    }
}

DateTimeFormatter :解析和格式化日期或时间的类

1.获取对象的方式,通过静态方法ofPattern("yyyy-MM-dd");
	DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
	LocalDateTime now = LocalDateTime.now();
2.format()方法把一个日期对象的默认格式 格式化成指定的格式
	String format1 = dateFormat.format(now);
	System.out.println(format1);
3.格式化日期 方式2使用日期类中的format方法 传入一个日期格式化类对象

	LocalDateTime now1 = LocalDateTime.now();
	使用日期类中的format方法 传入一个日期格式化类对象
	使用DateTimeFormatter中提供好的日期格式常量
	now1.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
4.使用自定义的日期格式格式化字符串
	DateTimeFormatter timeFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");//自定义一个日期格式
	String time = now1.format(timeFormat);
	System.out.println(time);

5. 把一个日期字符串转成日期对象
	使用日期类中的parse方法传入一个日期字符串,传入对应的日期格式化类
	DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
	LocalDateTime parse = LocalDateTime.parse(time, timeFormat);
	System.out.println(parse);
public class Test2 {
    public static void main(String[] args) {
        // DateTimeFormatter JDK1.8 提供的格式化日期的类
        DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy年MM月dd日");

        //对日前进行格式化
        LocalDate now = LocalDate.now();
        String format = now.format(dateFormat);
        System.out.println(format);

        //方式2
        String format1 = dateFormat.format(now);
        System.out.println(format1);
    }
}

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

用法和 LocalDate、 LocalTime、 LocalDateTime 一样 只不过ZonedDate,ZonedTime、ZonedDateTime 这三个带有当前系统的默认时区
public class Test3 {
    public static void main(String[] args) {
        //  用法和 LocalDate、LocalTime、LocalDateTime 一样 只不过ZonedDate, ZonedTime、ZonedDateTime 这三个带有当前系统的默认时区
        //ZonedDate,  LocalDate
        //ZonedTime、  LocalTime
        //ZonedDateTime : LocalDateTime
        ZonedDateTime now = ZonedDateTime.now();
        System.out.println(now);
        LocalDateTime now1 = LocalDateTime.now();
        System.out.println(now1);
    }
}

ZoneID 世界时区类

1.获取世界各个地方的时区的集合 的方法getAvailableZoneIds()
	使用ZoneID中的静态方法getAvailableZoneIds();来获取
	例如:Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();
2.获取系统默认时区的ID
	ZoneId zoneId = ZoneId.systemDefault(); //Asia/Shanghai
3.获取带有时区的日期时间对象
	//创建日期对象
	LocalDateTime now = LocalDateTime.now();
	//获取不同国家的日期时间根据各个地区的时区ID名创建对象
	ZoneId timeID = ZoneId.of("Asia/Shanghai");
	//根据时区ID获取带有时区的日期时间对象
	ZonedDateTime time = now.atZone(timeID);
	System.out.println(time);
	//方式2 通过时区ID 获取日期对象
	LocalDateTime now2 = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
	System.out.println(now2);
public class Test4 {
    public static void main(String[] args) {
        //ZoneId
        ZoneId zoneId = ZoneId.systemDefault();
        Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();
       /* for (String availableZoneId : availableZoneIds) {
            System.out.println(availableZoneId);
        }*/
        ZoneId id = ZoneId.of("America/Toronto");
        LocalDateTime now = LocalDateTime.now(id);
        System.out.println(now);
    }
}
   //方式2
        String format1 = dateFormat.format(now);
        System.out.println(format1);
    }
}

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

用法和 LocalDate、 LocalTime、 LocalDateTime 一样 只不过ZonedDate,ZonedTime、ZonedDateTime 这三个带有当前系统的默认时区
public class Test3 {
    public static void main(String[] args) {
        //  用法和 LocalDate、LocalTime、LocalDateTime 一样 只不过ZonedDate, ZonedTime、ZonedDateTime 这三个带有当前系统的默认时区
        //ZonedDate,  LocalDate
        //ZonedTime、  LocalTime
        //ZonedDateTime : LocalDateTime
        ZonedDateTime now = ZonedDateTime.now();
        System.out.println(now);
        LocalDateTime now1 = LocalDateTime.now();
        System.out.println(now1);
    }
}

ZoneID 世界时区类

1.获取世界各个地方的时区的集合 的方法getAvailableZoneIds()
	使用ZoneID中的静态方法getAvailableZoneIds();来获取
	例如:Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();
2.获取系统默认时区的ID
	ZoneId zoneId = ZoneId.systemDefault(); //Asia/Shanghai
3.获取带有时区的日期时间对象
	//创建日期对象
	LocalDateTime now = LocalDateTime.now();
	//获取不同国家的日期时间根据各个地区的时区ID名创建对象
	ZoneId timeID = ZoneId.of("Asia/Shanghai");
	//根据时区ID获取带有时区的日期时间对象
	ZonedDateTime time = now.atZone(timeID);
	System.out.println(time);
	//方式2 通过时区ID 获取日期对象
	LocalDateTime now2 = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
	System.out.println(now2);
public class Test4 {
    public static void main(String[] args) {
        //ZoneId
        ZoneId zoneId = ZoneId.systemDefault();
        Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();
       /* for (String availableZoneId : availableZoneIds) {
            System.out.println(availableZoneId);
        }*/
        ZoneId id = ZoneId.of("America/Toronto");
        LocalDateTime now = LocalDateTime.now(id);
        System.out.println(now);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值