JAVA8学习备忘录

8 篇文章 0 订阅

java8特点说明:

速度更快
代码更少(增加了新的语法 Lambda 表达式)  强大的 Stream API
便于并行
最大化减少空指针异常 Optional
其中最为核心的为 Lambda 表达式与Stream API

1. Lambda 表达式

1.1.为什么使用 Lambda 表达式

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

package com.wyz.java8;

import org.junit.Test;

import java.util.*;

public class TestLambda01 {
    //原来的匿名内部类
    @Test
    public void test1() {
        Comparator com = new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return Integer.compare(o1, o2);
            }
            @Override
            public boolean equals(Object obj) {
                return false;
            }
        };
        TreeSet<Integer> ts = new TreeSet<>(com);
    }

    //lambda 表达式
    @Test
    public void test2() {
        Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
        TreeSet<Integer> ts = new TreeSet<>(com);
    }

    List<Employee> employees = Arrays.asList(
            new Employee("张三",19,9999.99),
            new Employee("李四",39,19999.99),
            new Employee("王五",29,16999.99),
            new Employee("赵六",40,29999.99),
            new Employee("田七",41,29922.99)
            );
    //需求:获取当前公司员工中员工年龄大于35的员工信息
    @Test
    public void test3(){
        List<Employee> emps = filterEmployeeByAge(employees);
        for (Employee emp:emps) {
            System.out.println(emp);
        }
    }
    //需求:获取当前公司员工中员工工资大于10000的员工信息
    @Test
    public void test4(){
        List<Employee> emps = filterEmployeeBySaraly(employees);
        for (Employee emp:emps) {
            System.out.println(emp);
        }
    }
    public  List<Employee> filterEmployeeByAge(List<Employee> list){
        List<Employee> emps =   new ArrayList<>();
        for (Employee emp:list) {
            if(emp.getAge() >= 35){
                emps.add(emp);
            }
        }
        return emps;
    }
    public  List<Employee> filterEmployeeBySaraly(List<Employee> list){
        List<Employee> emps =   new ArrayList<>();
        for (Employee emp:list) {
            if(emp.getSalary() >10000){
                emps.add(emp);
            }
        }
        return emps;
    }
    //优化方式一:策略设计模式 (优点抽离了重复的业务代码,但每次增加时就得建立对应的实现类)
    public  List<Employee> filterEmployee(List<Employee> list,Mypredicate<Employee> mypredicate){
        List<Employee> emps =   new ArrayList<>();
        for (Employee emp:list) {
            if(mypredicate.test(emp)){
                emps.add(emp);
            }
        }
        return emps;
    }
    @Test
    public void test5(){
        List<Employee> list = filterEmployee(this.employees, new FilterEmployeeByAge());
        for (Employee emp:list) {
            System.out.println(emp);
        }
        System.out.println("------------------");
        List<Employee> list2 = filterEmployee(this.employees, new FilterEmployeeBySalary());
        for (Employee emp:list) {
            System.out.println(emp);
        }
    }

    //优化方式二:匿名内部类(解决策略模式的每次都建立类 使用匿名内部类)
    @Test
    public void test6(){
        List<Employee> list = filterEmployee(employees, new Mypredicate<Employee>() {
            @Override
            public boolean test(Employee employee) {
                return employee.getSalary() > 10000;
            }
        });
        for (Employee emp:list) {
            System.out.println(emp);
        }
    }
    //优化方式三:Lambda表达式(内部类的基础上精简代码)
    @Test
    public void test7(){
        List<Employee> list = filterEmployee(this.employees, (e) -> e.getSalary() > 10000);
        list.forEach(System.out :: println);
    }

    //优化方式四: stream API
    @Test
    public void test8(){
        employees.stream()
                .filter((e) -> e.getSalary() >10000)
                .forEach(System.out::println);
        System.out.println("-----------------");
        employees.stream()
                .map(Employee::getName)
                .forEach(System.out::println);
    }

}


package com.wyz.java8;

import java.util.Objects;

public class Employee {
    private String name;
    private Integer age;
    private Double salary;
    private Status status;

    public Employee() {
    }
    public Employee(Integer age) {
        this.age = age;
    }
    public Employee(String name, Integer age, Double salary) {
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    public Employee(String name, Integer age, Double salary, Status status) {
        this.name = name;
        this.age = age;
        this.salary = salary;
        this.status = status;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer 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 Objects.equals(name, employee.name) &&
                Objects.equals(age, employee.age) &&
                Objects.equals(salary, employee.salary) &&
                status == employee.status;
    }

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

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

    public enum Status{
        FREE,
        BUSY,
        VOCATION
    }
}

package com.wyz.java8;

public class FilterEmployeeByAge implements Mypredicate<Employee>{
    @Override
    public boolean test(Employee employee) {
        if(employee.getAge() >= 35){
          return true;
        }
        return false;
    }
}

package com.wyz.java8;

public class FilterEmployeeBySalary implements Mypredicate<Employee> {
    @Override
    public boolean test(Employee employee) {
        if(employee.getSalary()>=10000){
           return true;
        }
        return false;
    }
}

1.2.Lambda 表达式语法

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

  • 左侧:指定了 Lambda 表达式需要的所有参数
  • 右侧:指定了 Lambda 体,即 Lambda 表达式要执行的功能。
package com.wyz.java8;

import org.junit.Test;

import java.util.Comparator;
import java.util.function.Consumer;

/**
 * 一、lambda 表达式的基础语法:
 * java8中引入了一个新的操作符“->” 该操作符称为箭头操作符或Lambda操作符
 * 箭头操作符将Lambda表达式分成两部分:
 * 左侧:Lambda 表达式的参数列表
 * 右侧:Lambda表达式所需的执行的功能,即Lambda体
 * <p>
 * 语法格式一: 无参数,无返回值:() -> System.out.println("Hello Lambda!")
 * 语法格式二: 有一个参数,无返回值:(x) -> System.out.println(x)
 * 语法格式三: 若只有一个参数,小括号可以不写 x -> System.out.println(x)
 * 语法格式四: 有两个以上的参数,有返回值,lambda体中有多条语句。lambda体必须要大括号
 *              Comparator<Integer> com = (x, y) -> {
 *                          System.out.println("函数式接口");
 *                          return Integer.compare(x, y);
 *              };
 * 语法格式五:若Lambda 体中只有一条语句,大括号和return可以省略不写
 *              Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
 *
 * 语法格式六:Lambda表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出,数据类型。即“类型推断”
 *              Comparator<Integer> com = (Integer x, Integer y) -> Integer.compare(x, y);
 *
 *
 * 二、Lambda 表达式需要“函数式接口”的支持
 * 函数式接口:接口中只有一个抽象方法的接口,称为函数式接口。可以使用@FunctionalInterface 修饰,可以检查是否是函数式接口
 */

public class TestLambda02 {

    /**
     * 无参数,无返回值
     */

    @Test
    public void test1() {
        int num = 0;//jdk 1.7前,必须是final, jdk1.8后可以省略,底层会做final处理
        Runnable r = new Runnable() {
            @Override
            public void run() {
                System.out.println("Hello Lambda!" + num);
            }
        };
        r.run();
        System.out.println("----------");
        Runnable r1 = () -> System.out.println("Hello Lambda!");
        r1.run();
    }

    /**
     * 有一个参数,无返回值 若只有一个参数,小括号可以不写
     */

    @Test
    public void test2() {
//        Consumer<String> con = (x) -> System.out.println(x);
        Consumer<String> con = x -> System.out.println(x);

        con.accept("翀");
    }

    /**
     * 有两个以上的参数,有返回值,lambda体中有多条语句。lambda体必须要大括号
     */
    @Test
    public void test3() {
        Comparator<Integer> com = (x, y) -> {
            System.out.println("函数式接口");
            return Integer.compare(x, y);
        };
        int compare = com.compare(10, 100);
        System.out.println(compare);
    }

    /**
     * 若Lambda 体中只有一条语句,大括号和return可以省略不写
     */
    @Test
    public void test4(){
        Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
        int compare = com.compare(10, 8);
        System.out.println(compare);
    }

    /**
     * 需求:对一个数进行运算
     */
    @Test
    public void test5(){
        Integer num = operation(100, (x) -> x * x);
        System.out.println(num);
        System.out.println(operation(100, (y) -> y +200));
    }
    public Integer operation(Integer num,MyFun mf){
        return mf.getValue(num);
    }
}

2. 函数式接口

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

作为参数传递 Lambda 表达式:为了将 Lambda 表达式作为参数传递,接收Lambda 表达式的参数类型必须是与该 Lambda 表达式兼容的函数式接口的类型。
在这里插入图片描述
在这里插入图片描述

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

在这里插入图片描述

package com.wyz.java8;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * java8内置的四大核心函数式接口:
 * <p>
 * Consumer<T> :消费型接口
 * void accept(T t);
 * <p>
 * Supplier<T> :供给型接口
 * T get();
 * <p>
 * Function<T,R>:函数型接口
 * R apply(T t);
 * <p>
 * Predicate<T>: 断言型接口
 * boolean test(T t);
 */
public class TestLambda03 {

    /**
     * Consumer<T> :消费型接口
     */
    @Test
    public void test1() {
        happy(10000, (m) -> System.out.println("消费了" + m + "元!"));
    }

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

    /**
     * Supplier<T> :供给型接口
     * 需求:产生一些整数,并放入集合中
     */
    @Test
    public void test2() {
        List<Integer> numList = getNumList(10, () -> new Random().nextInt(100));
        for (Integer num : numList) {
            System.out.println(num);
        }
    }

    public List<Integer> getNumList(int num, Supplier<Integer> supplier) {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            Integer n = supplier.get();
            list.add(n);
        }
        return list;
    }

    /**
     * Function<T,R>:函数型接口
     * 需求:用于处理字符串
     */
    @Test
    public void test3() {
        String newStr = strHandler("\t\t翀\t", (str) -> str.trim());
        System.out.println(newStr);
        String newStr1 = strHandler("abcdwe", (str) -> str.toUpperCase());
        System.out.println(newStr1);
    }

    public String strHandler(String str, Function<String, String> function) {
        return function.apply(str);
    }

    /**
     * Predicate<T>: 断言型接口
     * 需求:将满足条件的字符串放到集合中
     */
    @Test
    public void test4() {
        List<String> list = Arrays.asList("hello", "wyz", "Lambda", "www","ok");
        List<String> strList = filterStr(list, (x) -> x.length() > 3);
        for (String str:strList) {
            System.out.println(str);
        }
    }

    public List<String> filterStr(List<String> list, Predicate<String> predicate) {
        List<String> strList = new ArrayList<>();
        for (String str : list) {
            if (predicate.test(str)) {
                strList.add(str);
            }
        }
        return strList;
    }
}


2.4其他接口

在这里插入图片描述

3. 方法引用与构造器引用

3.1.方法引用

当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用!(实现抽象方法的参数列表,必须与方法引用方法的参数列表保持一致!)
方法引用:使用操作符 “::” 将方法名和对象或类的名字分隔开来。
如下三种主要使用情况:

  • 对象::实例方法
  • 类::静态方法
  • 类::实例方法
3.2.构造器引用

格式: ClassName::new
与函数式接口相结合,自动与函数式接口中方法兼容。
可以把构造器引用赋值给定义的方法,与构造器参数列表要与接口中抽象方法的参数列表一致!

3.3.数组引用

格式: type[] :: new

package com.wyz.java8;

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;

/**
 * 一、方法引用:若Lambda体中的内容有方法已经实现了,我们可以使用“方法引用”
 * (可以理解为方法引用是Lambda表达式的另外一种表现形式)
 * <p>
 * 主要有三种语法格式:
 * 1.对象::实例方法名
 * 2.类::静态方法名
 * 3.类::实例方法名
 * <p>
 * 注意:
 * 1.Lambda体中调用方法的参数列表与返回值类型,要与函数式接口中抽象方法的参数列表和返回值类型保持一致!
 * 2.若Lambda参数列表中的第一个参数是实例方法的调用者,而第二个参数是实例方法的参数时,可以使用className::method
 * 例如:(x, y) -> x.equals(y) <==> String::equals
 * <p>
 * 二、构造器引用:
 * 格式:ClassName::new
 * <p>
 * 注意:需要调用的构造器的参数列表要与函数式接口中抽象方法的参数列表保持一致
 * <p>
 * 三、数组引用
 * Type[]::new
 */
public class TestMethodRef {

    /**
     * 对象::实例方法名
     */
    @Test
    public void test1() {
        PrintStream out1 = System.out;
        Consumer<String> consumer = (x) -> out1.println(x);


        PrintStream out = System.out;
        Consumer<String> consumer1 = out::println;

        Consumer<String> consumer2 = System.out::println;
        consumer2.accept("sssssxxxxx");
    }

    @Test
    public void test2() {
        Employee employee = new Employee();
        Supplier<String> supplier = () -> employee.getName();
        String s = supplier.get();
        System.out.println(s);

        Supplier<String> supplier1 = employee::getName;
        String s1 = supplier1.get();
        System.out.println(s1);

    }

    /**
     * 类::静态方法名
     */
    @Test
    public void test3() {
        Comparator<Integer> comparator = (x, y) -> Integer.compare(x, y);

        Comparator<Integer> comparator1 = Integer::compare;
        int compare = comparator1.compare(100, 101);
        System.out.println(compare);

    }

    /**
     * 类::实例方法名
     */
    @Test
    public void test4() {
        BiPredicate<String, String> bp = (x, y) -> x.equals(y);

        BiPredicate<String, String> bp2 = String::equals;
        boolean b = bp2.test("a", "a");
        System.out.println(b);
    }

    /**
     * 构造器引用
     */
    @Test
    public void Test5() {
        Supplier<Employee> supplier = () -> new Employee();

        Supplier<Employee> supplier1 = Employee::new;
        Employee employee = supplier1.get();
        System.out.println(employee);

    }

    @Test
    public void test6() {
        Function<Integer, Employee> function = (x) -> new Employee(x);
        Function<Integer, Employee> function1 = Employee::new;
        Employee employee = function1.apply(101);
        System.out.println(employee);
    }

    /**
     * 数组引用
     */
    @Test
    public void test7() {
        Function<Integer, String[]> function = (x) -> new String[x];

        String[] strings = function.apply(10);
        System.out.println(strings.length);

        Function<Integer, String[]> function1 = String[]::new;
        String[] strings1 = function1.apply(20);
        System.out.println(strings1.length);

    }
}

4. Stream API

Java8中有两大最为重要的改变。第一个是 Lambda 表达式;另外一个则是 Stream API(java.util.stream.*)。Stream 是 Java8 中处理集合的关键抽象概念,它可以指定你希望对
集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。使用Stream API 对集合数据进行操作,就类似于使用 SQL 执行的数据库查询。也可以使用 Stream API 来并行执行操作。简而言之,Stream API 提供了一种高效且易于使用的处理数据的方式。

4.1.什么是 Stream

流(Stream) 到底是什么呢?
是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列。
“集合讲的是数据,流讲的是计算!”
注意:
①Stream 自己不会存储元素。
②Stream 不会改变源对象。相反,他们会返回一个持有结果的新Stream。
③Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。

4.2.Stream 的操作三个步骤
  • 创建 Stream
    一个数据源(如:集合、数组),获取一个流
  • 中间操作
    一个中间操作链,对数据源的数据进行处理
  • 终止操作(终端操作)
    一个终止操作,执行中间操作链,并产生结果
    在这里插入图片描述
4.3.创建 Stream

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

  • default Stream stream() : 返回一个顺序流
  • default Stream parallelStream() : 返回一个并行流
4.3.1由数组创建流

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)
4.3.2.由值创建流

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

  • public static Stream of(T… values) : 返回一个流
4.3.2 由函数创建流:创建无限流

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

  • 迭代
    public static Stream iterate(final T seed, final UnaryOperator f)
  • 生成
    public static Stream generate(Supplier s) :
4.4.Stream 的中间操作

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

4.5.Stream 的终止操作

终端操作会从流的流水线生成结果。其结果可以是任何不是流的值,例如:List、Integer,甚至是 void
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

4.6并行流与串行流

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

package com.wyz.java8;

import org.junit.Test;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 一、stream的三个操作步骤:
 * 1.创建Stream
 * ①.可以通过Collection系列集合提供的串行的stream()或并行的parallelStream()
 * ②.通过Arrays中的静态方法stream()获取数组流
 * ③.通过Stream类中的静态方法of()
 * ④.创建无限流 (迭代|生成)
 * 2.中间操作
 *
 * * 筛选和切片
 * * filter -- 接收Lambda,从流中排除某些元素。
 *      * limit -- 截断流,使其元素不超过给定的数量
 *      * skip(n) -- 跳过元素,返回一个扔掉了前n个元素的流。若流中元素不足n个,则返回一个空流。与limit(n) 互补。
 *      * distinct -- 筛选,通过流所生成元素的hashCode() 和 equals() 去除重复元素。
 * * 映射
 *      * map -- 接收Lambda,将元素转换成其他形式或提取信息。
 *      *          接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
 *      * flatMap -- 接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流
 * * 排序
 *      * sorted() --- 自然排序(Comparable)
 *      * sorted(Comparator com) -- 定制排序(Comparator )
 * * 归约
 *      * reduce(T identity,BinaryOprator) / reduce(BinaryOprator)
 *      *  可以将流中元素反复结合起来,得到一个值。
 *
 * * 收集
 *      * collect -- 将流传成其他形式。接收一个Collector接口的实现,用于给Stream中元素做汇总的方法。
 * 3.终止操作(终端操作)
 *
 */
public class TestStreamAPI01 {
    List<Employee> employees = Arrays.asList(
            new Employee("张三", 19, 9999.99, Employee.Status.FREE),
            new Employee("李四", 39, 19999.99, Employee.Status.BUSY),
            new Employee("王五", 29, 16999.99, Employee.Status.FREE),
            new Employee("赵六", 40, 29999.99, Employee.Status.VOCATION),
            new Employee("赵六", 40, 29999.99, Employee.Status.VOCATION),
            new Employee("赵六", 40, 29999.99, Employee.Status.VOCATION),
            new Employee("赵六", 40, 29999.99, Employee.Status.VOCATION),
            new Employee("田七", 41, 29922.99, Employee.Status.BUSY)
    );

    /**
     * 创建Stream
     */
    @Test
    public void test1() {
        //1.可以通过Collection系列集合提供的串行的stream()或并行的parallelStream()
        List<String> list = new ArrayList<>();
        Stream<String> stream1 = list.stream();

        //2.通过Arrays中的静态方法stream()获取数组流
        Employee[] employees = new Employee[10];
        Stream<Employee> stream2 = Arrays.stream(employees);

        //3.通过Stream类中的静态方法of()
        Stream<String> stream3 = Stream.of("aa", "bb", "cc");

        //4.创建无限流
        //迭代
        Stream<Integer> stream4 = Stream.iterate(0, (x) -> x + 2);
        stream4.limit(10).forEach(System.out::println);
        //生成
        Stream.generate(() -> new Random().nextInt(100))
                .limit(5)
                .forEach(System.out::println);

    }

    /**
     * 中间操作:不会执行任何操作
     * 筛选和切片
     * filter -- 接收Lambda,从流中排除某些元素。
     * limit -- 截断流,使其元素不超过给定的数量
     * skip(n) -- 跳过元素,返回一个扔掉了前n个元素的流。若流中元素不足n个,则返回一个空流。与limit(n) 互补。
     * distinct -- 筛选,通过流所生成元素的hashCode() 和 equals() 去除重复元素。
     */

    //内部迭代:迭代操作由Stream API完成
    @Test
    public void test2() {
        //filter
        Stream<Employee> stream1 = employees.stream()
                .filter((e) -> {
                    System.out.println("stream api 的中间操作");
                    return e.getAge() > 35;
                });
        //终止操作:一次性执行全部内容,即”惰性求职“
        stream1.forEach(System.out::println);
    }

    //外部迭代:
    @Test
    public void test3() {
        Iterator<Employee> it = employees.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }

    //limit()
    @Test
    public void test4() {
        employees.stream()
                .filter((e) -> {
                    System.out.println("短路!");
                    return e.getSalary() > 10000;
                })
                .limit(2)
                .forEach(System.out::println);
    }

    //skip()
    @Test
    public void test5() {
        employees.stream()
                .filter((e) -> e.getSalary() > 10000)
                .skip(2)
                .forEach(System.out::println);
    }

    //distinct() 注意Employee对象要重写 hashCode 和 equals 方法
    @Test
    public void test6() {
        employees.stream()
                .filter((e) -> e.getSalary() > 10000)
                .distinct()
                .forEach(System.out::println);
    }

    /**
     * 映射
     * map -- 接收Lambda,将元素转换成其他形式或提取信息。
     * 接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
     * flatMap -- 接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流
     */
    @Test
    public void test7() {
        List<String> list = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");
        list.stream()
                .map((str) -> str.toUpperCase())
                .forEach(System.out::println);

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

        employees.stream()
                .map(Employee::getName)
                .forEach(System.out::println);

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

        //未使用flatMap
        Stream<Stream<Character>> streamStream = list.stream()
                .map(TestStreamAPI01::filterCharacter);
        streamStream.forEach((sm) ->{
            sm.forEach(System.out::println);
        });
        //使用flatMap
        Stream<Character> characterStream = list.stream()
                .flatMap(TestStreamAPI01::filterCharacter);
        characterStream.forEach(System.out::println );


    }

    public static Stream<Character> filterCharacter(String str) {
        List<Character> list = new ArrayList<>();
        for (Character ch : str.toCharArray()) {
            list.add(ch);
        }
        return list.stream();
    }
    /**
     * 排序
     * sorted() --- 自然排序(Comparable)
     * sorted(Comparator com) -- 定制排序(Comparator )
     */
    @Test
    public void test8(){
        List<String> list = Arrays.asList("ccc", "eee", "qqq", "aaa", "ddd");
        list.stream()
                .sorted()
                .forEach(System.out::println);

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

        employees.stream()
                .sorted((e1,e2) -> {
                    if(e1.getAge().equals(e2.getAge())){
                       return e1.getName().compareTo(e2.getName());
                    }else {
                        //正序
                        return e1.getAge().compareTo(e2.getAge());
                        //倒序
//                        return -e1.getAge().compareTo(e2.getAge());
                    }
                })
                .forEach(System.out::println);
    }
    /**
     * 查找与匹配
     * allMatch --- 检查是否匹配所有元素
     * anyMatch --- 检查是否至少匹配一个元素
     * noneMatch --- 检查是否没有匹配所有元素
     * findFirst --- 返回第一个元素
     * count --- 返回流中元素的总个数
     * max --- 返回流中最大值
     * min --- 返回流中最小值
     */
    @Test
    public void test9(){
        boolean b1 = employees.stream()
                .allMatch((e) -> e.getStatus().equals(Employee.Status.BUSY));
        System.out.println(b1);
        System.out.println("----------------");
        boolean b2 = employees.stream()
                .anyMatch((e) -> e.getStatus().equals(Employee.Status.BUSY));
        System.out.println(b2);
        System.out.println("----------------");

        long count = employees.stream().count();
        System.out.println(count);
        System.out.println("----------------");

        boolean b4 = employees.stream()
                .noneMatch((e) -> e.getStatus().equals(Employee.Status.BUSY));
        System.out.println(b4);
        System.out.println("----------------");

        Optional<Employee> optionalEmployee = employees.stream()
                .sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()))
                .findFirst();
        System.out.println(optionalEmployee.get());
        System.out.println("----------------");

        Optional<Employee> first = employees.parallelStream()
                .filter((e) -> e.getStatus().equals(Employee.Status.BUSY))
                .findAny();
        System.out.println(first.get());
        System.out.println("----------------");

        Optional<Employee> max = employees.stream()
                .max((e1, e2) -> Double.compare(e1.getSalary() ,e2.getSalary()));
        System.out.println(max.get());
        System.out.println("----------------");

        Optional<Double> min = employees.stream()
                .map(Employee::getSalary)
                .min(Double::compare);
        System.out.println(min);
        System.out.println("----------------");
    }
    /**
     * 归约
     * reduce(T identity,BinaryOprator) / reduce(BinaryOprator)
     *  可以将流中元素反复结合起来,得到一个值。
     */
    @Test
    public void test10(){
        List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
        Integer sum = list.stream()
                .reduce(0, (x, y) -> x + y);
        System.out.println(sum);
        System.out.println("-----------------");
        Optional<Double> salarySum = employees.stream()
                .map(Employee::getSalary)
                .reduce(Double::sum);
        System.out.println(salarySum.get());

    }
    /**
     * 收集
     * collect -- 将流传成其他形式。接收一个Collector接口的实现,用于给Stream中元素做汇总的方法。
     */
    @Test
    public void test11(){
        List<String> list = employees.stream()
                .map(Employee::getName)
                .collect(Collectors.toList());
        list.forEach(System.out::println);

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

        Set<String> set = employees.stream()
                .map(Employee::getName)
                .collect(Collectors.toSet());
        set.forEach(System.out::println);

        System.out.println("--------------------");
        HashSet<String> hashSet = employees.stream()
                .map(Employee::getName)
                .collect(Collectors.toCollection(HashSet::new));
        hashSet.forEach(System.out::println);
        System.out.println("--------------------");

        //总数
        Long count = employees.stream()
                .collect(Collectors.counting());
        System.out.println(count);

        System.out.println("总数--------------------");
        
        //平均值
        Double avg = employees.stream()
                .collect(Collectors.averagingDouble(Employee::getSalary));
        System.out.println(avg);
        System.out.println("平均值--------------------");
        //总和
        Double  sum = employees.stream()
                .collect(Collectors.summingDouble(Employee::getSalary));
        System.out.println(sum);
        System.out.println("总和--------------------");

        //最大值
        Optional<Employee> max = employees.stream()
                .collect(Collectors.maxBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));
        System.out.println(max.get().getSalary());
        System.out.println("最大值--------------------");

        //最小值
        Optional<Double> min = employees.stream()
                .map(Employee::getSalary)
                .collect(Collectors.minBy(Double::compare));
        System.out.println(min.get());
        System.out.println("最小值--------------------");
        //分组
        Map<Employee.Status, List<Employee>> group = employees.stream()
                .collect(Collectors.groupingBy(Employee::getStatus));
        for (Map.Entry<Employee.Status, List<Employee> > entry: group.entrySet()) {
            System.out.println(entry.getKey() +":"+entry.getValue());
        }
        System.out.println("分组--------------------");

        //多几分组
        Map<Employee.Status, Map<String, List<Employee>>> muGroup = employees.stream()
                .collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy(
                        (e) -> {
                            if (((Employee) e).getAge() > 35) {
                                return "青年";
                            } else if (((Employee) e).getAge() <= 50) {
                                return "老年";
                            } else {
                                return "老年";
                            }
                        }
                )));
        System.out.println(muGroup);
        System.out.println("多级分组--------------------");

        //分区
        Map<Boolean, List<Employee>> part = employees.stream()
                .collect(Collectors.partitioningBy((e) -> e.getAge() < 30));
        System.out.println(part);
        System.out.println("分区--------------------");

        //连接
        String join = employees.stream()
                .map(Employee::getName)
                .collect(Collectors.joining("|"));
        System.out.println(join);
        System.out.println("连接--------------------");

    }
    /**
     * 1.给定一个数字列表,如何返回一个由每个数的平方构成的列表呢?
     * ,给定【1,2,3,4,5】 ,应该返回【1,4,9,16,25】
     */
    @Test
    public void test12(){
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
        list.stream()
                .map((x) -> x*x)
        .forEach(System.out::println);
    }
    /**
     * 怎样用map和reduce 方法数一数该流中有多少个Employee?
     */
    @Test
    public void test13(){
        Optional<Integer> sum = employees.stream()
                .map((e) -> 1)
                .reduce(Integer::sum);
        System.out.println(sum.get());
    }
}

5. 接口中的默认方法与静态方法

.Java 8中允许接口中包含具有具体实现的方法,该方法称为“默认方法”,默认方法使用 default 关键字修饰
在这里插入图片描述

5.1.接口默认方法的”类优先”原则

若一个接口中定义了一个默认方法,而另外一个父类或接口中又定义了一个同名的方法时

  • 选择父类中的方法。如果一个父类提供了具体的实现,那么接口中具有相同名称和参数的默认方法会被忽略。
  • 接口冲突。如果一个父接口提供一个默认方法,而另一个接也提供了一个具有相同名称和参数列表的方法(不管方法是否是默认方法),那么必须覆盖该方法来解决冲突
    在这里插入图片描述
5.2.接口中的静态方法

Java8 中,接口中允许添加静态方法。
在这里插入图片描述

6. 新时间日期 API

java8以前的日期有线程安全问题,java8解决了日期线程安全问题

package com.wyz.java8;

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

public class TestDateFormatThreadLocal {
    private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>(){
        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat("yyyyMMdd");
        }
    };
    public static Date concert(String source) throws ParseException {
        return df.get().parse(source);

    }
}

package com.wyz.java8;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

/**
 * 以前 date线程安全问题和解决
 * jdk1.8 后date没有线程安全问题
 */
public class TestSimpleDateFormat {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        /*
        线程安全
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Callable<Date> callable = new Callable<Date>() {
            @Override
            public Date call() throws Exception {
                return sdf.parse("20161218");
            }
        };*/
        //解决线程安全
        Callable<Date> callable = new Callable<Date>() {
            @Override
            public Date call() throws Exception {
                return TestDateFormatThreadLocal.concert("20180213");
            }
        };
        ExecutorService pool = Executors.newFixedThreadPool(10);
        List<Future<Date>> results = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            results.add(pool.submit(callable));
        }
        for (Future<Date> future:results) {
            System.out.println(future.get());
        }
        pool.shutdown();

        //java 1.8
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");

        Callable<LocalDate> task = new Callable<LocalDate>() {
            @Override
            public LocalDate call() throws Exception {
                return LocalDate.parse("20180214",dtf);
            }
        };
        ExecutorService pool1 = Executors.newFixedThreadPool(10);
        List<Future<LocalDate>> results1 = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            results1.add(pool1.submit(task));
        }
        for (Future<LocalDate> future:results1) {
            System.out.println(future.get());
        }
        pool1.shutdown();
    }
}

6.1.使用 LocalDate、LocalTime、LocalDateTime

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

6.2.Instant 时间戳

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

6.3.Duration 和 Period
  • Duration:用于计算两个“时间”间隔
  • Period:用于计算两个“日期”间隔
6.4日期的操纵
  • TemporalAdjuster : 时间校正器。有时我们可能需要获取例如:将日期调整到“下个周日”等操作。
  • TemporalAdjusters : 该类通过静态方法提供了大量的常用 TemporalAdjuster 的实现。
6.4.解析与格式化

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

  • 预定义的标准格式
  • 语言环境相关的格式
  • 自定义的格式
6.5.时区的处理

Java8 中加入了对时区的支持,带时区的时间为分别为:
ZonedDate、ZonedTime、ZonedDateTime 其中每个时区都对应着 ID,地区ID都为 “{区域}/{城市}”的格式
例如 :Asia/Shanghai 等

  • ZoneId:该类中包含了所有的时区信息
  • getAvailableZoneIds() : 可以获取所有时区时区信息
  • of(id) : 用指定的时区信息获取 ZoneId 对象
    在这里插入图片描述
package com.wyz.java8;

import org.junit.Test;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Set;

public class TestLocalDateTime {
    /**
     * 1.  LocalDate LocalTime LocalDateTime
     */
    @Test
    public void test1() {
        LocalDateTime ldt = LocalDateTime.now();
        System.out.println(ldt);

        LocalDateTime ldt2 = LocalDateTime.of(2019, 10, 19, 12, 22, 33, 222);
        System.out.println(ldt2);
        //加
        LocalDateTime ldt3 = ldt.plusYears(2);
        System.out.println(ldt3);
        //减
        LocalDateTime ldt4 = ldt.minusMonths(2);
        System.out.println(ldt4);
        //获取年
        System.out.println(ldt.getYear());
        //获取月
        System.out.println(ldt.getMonthValue());
    }

    /**
     * 2.Instant:时间戳(以UNIX元年:1970年1月1日00:00:00之间的毫秒值)
     */
    @Test
    public void test2() {
        Instant ins1 = Instant.now();
        //默认获取UTC时区
        //2020-06-23T02:35:01.529Z
        System.out.println(ins1);

        //时区偏移
        //2020-06-23T10:35:01.529+08:00
        OffsetDateTime ott = ins1.atOffset(ZoneOffset.ofHours(8));
        System.out.println(ott);
        //毫秒值
        //1592879701529
        System.out.println(ins1.toEpochMilli());
        //相较于元年偏移60秒
        //1970-01-01T00:01:00Z
        Instant ins2 = Instant.ofEpochSecond(60);
        System.out.println(ins2);
    }
    /**
     * Duration:计算两个“时间”之间的间隔
     * Period:计算两个“日期”之间的间隔
     */
    @Test
    public void test3() throws InterruptedException {
        Instant start = Instant.now();
        Thread.sleep(1000);
        Instant end = Instant.now();
        Duration d = Duration.between(start, end);
        //秒
        System.out.println(d.getSeconds());
        //毫秒
        System.out.println(d.toMillis());
        //纳秒
        System.out.println(d.getNano());

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

        LocalTime localTime1 = LocalTime.now();
        Thread.sleep(1000);
        LocalTime localTime2 = LocalTime.now();
        System.out.println(Duration.between(localTime1,localTime2).toMillis());

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

        LocalDate localDate1 = LocalDate.now();
        LocalDate localDate2 = LocalDate.of(2020, 12, 30);
        Period period = Period.between(localDate1, localDate2);
        System.out.println(period);
        System.out.println(period.getYears());
        System.out.println(period.getMonths());
        System.out.println(period.getDays());
    }
    /**
     * TemporalAdjuster:
     * TemporalAdjuster : 时间校正器。有时我们可能需要获取
     *                      例如:将日期调整到“下个周日”等操作。
     * TemporalAdjusters : 该类通过静态方法提供了大量的常用 TemporalAdjuster 的实现
     */
    @Test
    public void test4(){
        LocalDateTime ldt = LocalDateTime.now();
        //2020-06-23T10:55:15.158
        System.out.println(ldt);
        //将月中的日期指定为某值
        LocalDateTime ldt2 = ldt.withDayOfMonth(10);
        //2020-06-10T10:55:15.158
        System.out.println(ldt2);

        System.out.println("-------------------");
        //获取下一个周日
        LocalDateTime ldt3 = ldt.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
        //2020-06-28T11:00:04.290
        System.out.println(ldt3);

        //自定义 :下一个工作日
        LocalDateTime ldt5 = ldt.with((l) -> {
            LocalDateTime ldt4 = (LocalDateTime) l;
            //获取周几
            DayOfWeek dayOfWeek = ldt4.getDayOfWeek();
            if (dayOfWeek.equals(DayOfWeek.FRIDAY)) {
                return ldt4.plusDays(3);
            } else if (dayOfWeek.equals(DayOfWeek.SATURDAY)) {
                return ldt4.plusDays(2);
            } else {
                return ldt4.plusDays(1);
            }
        });
        //2020-06-24T11:06:01.711
        System.out.println(ldt5);
    }
    /**
     * DateTimeFormatter:
     * java.time.format.DateTimeFormatter 类:该类提供了三种
     * 格式化方法:
     *  预定义的标准格式
     *  语言环境相关的格式
     *  自定义的格式
     */
    @Test
    public void test5(){
        DateTimeFormatter dtf = DateTimeFormatter.ISO_DATE_TIME;
        DateTimeFormatter dtf2 = DateTimeFormatter.ISO_DATE;
        DateTimeFormatter dtf3 = DateTimeFormatter.ofPattern("yyyy--MM--dd");
        LocalDateTime now = LocalDateTime.now();
        String s = now.format(dtf);
        String s2 = now.format(dtf2);
        String s3 = now.format(dtf3);
        //2020-06-23T11:10:31.277
        System.out.println(s);
        //2020-06-23
        System.out.println(s2);
        //2020--06--23
        System.out.println(s3);

        System.out.println("---------------------");
        //字符串转时间
        LocalDateTime time = LocalDateTime.parse(s3, dtf2);
        System.out.println(time);

    }
    /**
     * 时区的处理:
     * ZonedDate、ZonedTime、ZonedDateTime
     * 其中每个时区都对应着 ID,地区ID都为 “{区域}/{城市}”的格式
     * 例如 :Asia/Shanghai 等
     * ZoneId:该类中包含了所有的时区信息
     * getAvailableZoneIds() : 可以获取所有时区时区信息
     * of(id) : 用指定的时区信息获取 ZoneId 对象
     */
    @Test
    public void test6(){
        //打印所有时区
        Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();
        availableZoneIds.forEach(System.out::println);
        System.out.println("-----------------");
        //获取某个时区
        LocalDateTime ldt = LocalDateTime.now(ZoneId.of("Asia/Tokyo"));
        //2020-06-23T14:55:02.375
        System.out.println(ldt);

        System.out.println("------------");
        //带时区的日期
        ZonedDateTime zdt = ldt.atZone(ZoneId.of("Asia/Tokyo"));
        //2020-06-23T14:55:02.375+09:00[Asia/Tokyo]
        System.out.println(zdt);
    }

}

7. 其他新特性

7.1.Optional 类

Optional 类(java.util.Optional) 是一个容器类,代表一个值存在或不存在,原来用 null 表示一个值不存在,现在 Optional 可以更好的表达这个概念。并且可以避免空指针异常。
常用方法:

  • Optional.of(T t) : 创建一个 Optional 实例
  • Optional.empty() : 创建一个空的 Optional 实例
  • Optional.ofNullable(T t):若 t 不为 null,创建 Optional 实例,否则创建空实例
  • isPresent() : 判断是否包含值
  • orElse(T t) : 如果调用对象包含值,返回该值,否则返回t
  • orElseGet(Supplier s) :如果调用对象包含值,返回该值,否则返回 s 获取的值
  • map(Function f): 如果有值对其处理,并返回处理后的Optional,否则返回 Optional.empty()
  • flatMap(Function mapper):与 map 类似,要求返回值必须是Optional
package com.wyz.java8;

import org.junit.Test;

import java.util.Optional;

/**
 * Optional<T> 类(java.util.Optional) 是一个容器类,代表一个值存在或不存在,
 * 原来用 null 表示一个值不存在,现在 Optional 可以更好的表达这个概念。并且
 * 可以避免空指针异常。
 * 常用方法:
 * Optional.of(T t) : 创建一个 Optional 实例
 * Optional.empty() : 创建一个空的 Optional 实例
 * Optional.ofNullable(T t):若 t 不为 null,创建 Optional 实例,否则创建空实例
 * isPresent() : 判断是否包含值
 * orElse(T t) : 如果调用对象包含值,返回该值,否则返回t
 * orElseGet(Supplier s) :如果调用对象包含值,返回该值,否则返回 s 获取的值
 * map(Function f): 如果有值对其处理,并返回处理后的Optional,否则返回 Optional.empty()
 * flatMap(Function mapper):与 map 类似,要求返回值必须是Optional
 */

public class TestOptional {

    //Optional.of(T t) : 创建一个 Optional 实例
    @Test
    public void test1() {
        Optional<Employee> op = Optional.of(new Employee());
        Employee employee = op.get();
        System.out.println(employee);
    }
    //Optional.empty() : 创建一个空的 Optional 实例
    @Test
    public void test2() {
        Optional<Employee> op = Optional.empty();
        Employee employee = op.get();
        System.out.println(employee);
    }
    //Optional.ofNullable(T t):若 t 不为 null,创建 Optional 实例,否则创建空实例
    @Test
    public void test3() {
        Optional<Employee> op = Optional.ofNullable(null);
        Employee employee = op.get();
        System.out.println(employee);
    }
    //isPresent() : 判断是否包含值
    @Test
    public void test4() {
        Optional<Employee> op = Optional.ofNullable(null);
        if(op.isPresent()){
            Employee employee = op.get();
            System.out.println(employee);
        }
    }
    //orElse(T t) : 如果调用对象包含值,返回该值,否则返回t
    @Test
    public void test5() {
        Optional<Employee> op = Optional.ofNullable(null);
        Employee employee = op.orElse(new Employee("张三", 18, 8888.88, Employee.Status.VOCATION));
        System.out.println(employee);
    }

    //orElseGet(Supplier s) :如果调用对象包含值,返回该值,否则返回 s 获取的值
    @Test
    public void test6() {
        Optional<Employee> op = Optional.ofNullable(null);
        Employee employee = op.orElseGet(()->new Employee());
        System.out.println(employee);
    }

    // map(Function f): 如果有值对其处理,并返回处理后的Optional,否则返回 Optional.empty()
    @Test
    public void test7() {
        Optional<Employee> op = Optional.ofNullable(new Employee("张三", 18, 8888.88, Employee.Status.VOCATION));
        Optional<String> s = op.map((e) -> e.getName());
        System.out.println(s.get());
        Optional<String> s1 = op.flatMap((e) -> Optional.of(e.getName()));
        System.out.println(s1.get());
    }


}

7.2.重复注解与类型注解

Java 8对注解处理提供了两点改进:可重复的注解及可用于类型的注解。
在这里插入图片描述

package com.wyz.java8;

import java.lang.annotation.*;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.ElementType.LOCAL_VARIABLE;

@Repeatable(value = MyAnnotations.class)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, TYPE_PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
     String value() default "ssss";
}
package com.wyz.java8;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.ElementType.LOCAL_VARIABLE;

@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotations {

    MyAnnotation[] value();
}

package com.wyz.java8;

import org.junit.Test;

import java.io.IOException;
import java.lang.reflect.Method;

/**
 *重复注解与类型注解
 */
public class TestAnnotation {
    @Test
    public void test() throws Exception  {
        Class<TestAnnotation> clazz = TestAnnotation.class;
        Method m = clazz.getMethod("show");
        MyAnnotation[] mas = m.getAnnotationsByType(MyAnnotation.class);
        for (MyAnnotation mya:mas) {
            //wyz
            //wya
            System.out.println(mya.value());
        }
    }

    @MyAnnotation("wyz")
    @MyAnnotation("wya")
    public void show(@MyAnnotation("aa") String s){

    }
}

8.了解 Fork/Join 框架

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

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

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

package com.wyz.java8;

import org.junit.Test;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

public class TestForkJoin {
    long l = 1000000000L;
    @Test
    public void test() {
        Instant start = Instant.now();
        ForkJoinPool pool = new ForkJoinPool();

        ForkJoinTask<Long> task = new ForkJoinCalculate(0, l);

        Long sum = pool.invoke(task);
        System.out.println(sum);

        Instant end = Instant.now();

        System.out.println("耗费时间:" + Duration.between(start, end).toMillis() + "毫秒");

    }

    /**
     * 普通for
     */
    @Test
    public void test2() {
        Instant start = Instant.now();
        long sum = 0;
        for (int i = 0; i <= l; i++) {
            sum += i;
        }
        System.out.println(sum);
        Instant end = Instant.now();

        System.out.println("耗费时间:" + Duration.between(start, end).toMillis() + "毫秒");
    }
    /**
     * java8并行流
     */
    @Test
    public void test3(){
        Instant start = Instant.now();
        long sum = LongStream.rangeClosed(0, l)
                .parallel()
                .reduce(0, Long::sum);
        System.out.println(sum);
        Instant end = Instant.now();

        System.out.println("耗费时间:" + Duration.between(start, end).toMillis() + "毫秒");
    }
}

Java备忘录课程设计是一个以Java语言为基础,设计并实现一个备忘录应用的课程项目。备忘录应用通常用于用户记录和管理重要的信息和事件,帮助用户在日常生活更有效地组织和安排时间。 在设计这个备忘录应用时,我们需要考虑以下几个方面。 首先,我们需要设计一个用户界面,使用户能够方便地进行备忘录的添加、编辑和删除操作。可以使用Java的图形界面库,如Swing或JavaFX来实现用户界面。 其次,我们需要设计一个数据模型,用于存储备忘录的相关信息。可以使用Java的对象和集合来实现数据模型,在其定义备忘录的属性(如标题、内容、日期等)以及相应的操作方法(如添加、编辑和删除备忘录)。 然后,我们需要实现备忘录的数据持久化功能,以确保备忘录的信息能够长期保存。可以使用Java的文件操作或者数据库等技术来实现数据持久化。 此外,我们还可以考虑为备忘录应用添加一些其他的功能,如备忘录的分类和标签、提醒功能、搜索和过滤功能等,以提高用户体验。 最后,在实现备忘录应用的过程,我们还应该注重代码的可维护性和可扩展性。可以使用面向对象的设计原则和设计模式,如单一职责原则、开闭原则、工厂模式等来提高代码的质量和灵活性。 总之,Java备忘录课程设计是一个通过使用Java语言和相关技术实现一个备忘录应用的项目。通过这个项目,我们可以学习和应用Java的面向对象编程思想、图形界面编程和数据持久化等技术,提升我们的软件开发能力。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值