Java8 JDK8

1、为什么要学Java8?

1.1  简介

速度更快(底层的数据结构做了一些更新和改动,垃圾回收机制内存结构做了一些改动)

代码更少(增加了新的语法Lambda表达式)

强大的StreamAPI

便于并行

最大化减少空指针异常(Optional容器类)

1.2  主要内容

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

2、Lambda表达式

为什么要使用Lambda表达式?见代码TestLambda.java

2.1  什么是Lambda表达式?

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

Java8中引入了一个新的操作符”->”该操作符称为箭头操作符或Lambda操作符,箭头操作符将Lambda表达式拆分为两部分:

左侧:Lambda表达式的参数列表。对应接口中抽象方法的参数列表。

右侧:Lambda表达式中所需要执行的功能,即Lambda体。对应接口中抽象方法的实现。

2.2  Lambda表达式的基础语法

2.2.1  无参数,无返回值

    /*

     * Lambda表达式的基础语法:

     * 语法格式一:

     *     无参数,无返回值

     */

    @Test

    public void test1() {

       int num = 0;

      

       Runnable r = new Runnable() {

          

           @Override

           public void run() {

              System.out.println("Hello World" + num);

           }

       };

       r.run();

      

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

      

       Runnable r2 = () -> System.out.println("Hello Lambda!");

       r2.run();

    }

2.2.2  有一个参数,无返回值

    /*

     * 语法格式二:

     *     有一个参数:无返回值

     */

    @Test

    public void test2() {

       Consumer<String> con = (t) -> System.out.println(t);

       con.accept("Hello Lambda!");

    }

2.2.3  若只有一个参数,小括号可以省略不写

    /*

     * 语法格式三:

     *     若只有一个参数,小括号可以省略不写

     */

    @Test

    public void test3() {

       Consumer<String> con = t -> System.out.println(t);

       con.accept("Hello Lambda!");

    }

2.2.4  有两个以上的参数,有返回值,并且Lambda体中有多条语句

    /*

     * 语法格式四:

     *     有两个以上的参数,有返回值,并且Lambda体中有多条语句

     */

    @Test

    public void test4() {

       Comparator<Integer> com = (x, y) -> {

           System.out.println("Hello Lambda!");

           return Integer.compare(x, y);

       };

    }

2.2.5  若Lambda体中只有一条语句,return和大括号都可以省略不写

    /*

     * 语法格式五:

     *     若Lambda体中只有一条语句,return和大括号都可以省略不写

     */

    @Test

    public void test5() {

       Comparator<Integer> com = (x, y) -> Integer.compare(x, y);

    }

2.2.6  Lambda表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出数据类型,即“类型推断”

    /*

     * 语法格式六:

     *     Lambda表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出数据类型,即“类型推断”

     */

    @Test

    public void test6() {

       Comparator<Integer> com = (Integer x, Integer y) -> Integer.compare(x, y);

      

       show(new HashMap<>());// jdk1.8以后

    }

   

    public void show(Map<String, Integer> map) {

      

    }

2.3  Lambda表达式需要“函数式接口”的支持

2.3.1  什么是函数式接口?

接口中只有一个抽象方法的接口,称为函数式接口。

可以使用注解@FunctionalInterface修饰,可以检查是否是函数式接口。

2.3.2  使用函数式接口

MyFunction.java

@FunctionalInterface

public interface MyFunction<T> {

   

    public T getValue(T o);

   

}

测试类

    // 需求:对一个数进行运算

    @Test

    public void test7() {

       Integer result = operation(100, (x) -> x * x);

       System.out.println(result);

      

       result = operation(200, (y) -> y - 100);

       System.out.println(result);

    }

   

    public Integer operation(Integer num, MyFunction<Integer> mf) {

       return mf.getValue(num);

    }

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

2.4.1  Consumer<T> 消费型接口

    /*

     * Consumer<T> 消费型接口

     *      void accept(T t);

     */

    @Test

    public void test1() {

       happy(10000, (m) -> System.out.println("向天老师大宝剑" + m + "元"));

    }

   

    public void happy(double money, Consumer<Double> con) {

       con.accept(money);

    }

2.4.2  Supplier<T> 供给型接口

    /*

     * Supplier<T> 供给型接口

     *     T get();

     */

    // 需求:产生指定个数的整数,并放入集合中

    @Test

    public void test2() {

       List<Integer> numList = getNumList(10, () -> (int)(Math.random() * 100));

      

       for (Integer integer : numList) {

           System.out.println(integer);

       }

    }

   

    public List<Integer> getNumList(int num, Supplier<Integer> sup) {

       List<Integer> list = new ArrayList<>();

      

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

           Integer n = sup.get();

           list.add(n);

       }

      

       return list;

    }

2.4.3  Function<T, R> 函数型接口

    /*

     * Function<T, R> 函数型接口

     *     R apply(T t);

     */

    // 需求:用于处理字符串

    @Test

    public void test3() {

       String newStr = strHandler("  bjsxt   ", (str) -> str.trim());

       System.out.println(newStr);

      

       newStr = strHandler("bjsxt", (str) -> str.substring(2, 5));

       System.out.println(newStr);

    }

   

    public String strHandler(String str, Function<String, String> fun) {

       return fun.apply(str);

    }

2.4.4  Predicate<T> 断言型接口

    /*

     * Predicate<T> 断言型接口

     *     boolean test(T t);

     */

    // 需求:将满足条件的字符串,放入集合中

    @Test

    public void test4() {

       List<String> list = Arrays.asList("hello", "bjsxt", "Lambda", "www", "ok");

       List<String> strList = filterStr(list, (s) -> s.length() > 3);

      

       for (String string : strList) {

           System.out.println(string);

       }

    }

   

    public List<String> filterStr(List<String> list, Predicate<String> pre) {

       List<String> strList = new ArrayList<>();

      

       for (String string : list) {

           if(pre.test(string)) {

              strList.add(string);

           }

       }

      

       return strList;

    }

2.5  方法引用

若Lambda体中的内容有方法已经实现了,我们可以使用“方法引用”(可以立即为方法引用是Lambda表达式的另一种表现形式),主要有三种语法格式:

2.5.1  对象::实例方法名

    // 对象::实例方法名

    @Test

    public void test1() {

//消费型接口

       Consumer<String> con = (x) -> System.out.println(x);

      

       PrintStream ps = System.out;

       Consumer<String> con1 = ps::println;

      

       Consumer<String> con2 = System.out::println;

       con2.accept("bjsxt");

    }

   

    @Test

    public void test2() {

       Employee emp = new Employee();

       emp.setName("张三");

       emp.setAge(18);

//无形参 有返回 供给型接口

       Supplier<String> sup = () -> emp.getName();

       String str = sup.get();

       System.out.println(str);

      

       Supplier<Integer> sup2 = emp::getAge;

       int age = sup2.get();

       System.out.println(age);

    }

2.5.2  类::静态方法名

    // 类::静态方法名

    @Test

    public void test3() {

       Comparator<Integer> com = (x, y) -> Integer.compare(x, y);

      

       Comparator<Integer> com1 = Integer::compare;

    }

2.5.3  类::实例方法名

    // 类::实例方法名

    @Test

    public void test4() {

       BiPredicate<String, String> bp = (x, y) -> x.equals(y);

      

       BiPredicate<String, String> bp1 = String::equals;

    }

注意:

  1. Lambda体中调用方法的参数列表和返回值类型,要与函数式接口中抽象方法的函数列表和返回值类型保持一致。
  2. Lambda参数列表中的第一个参数是实例方法的调用者,第二个参数是实例方法的参数时,可以使用ClassName::method

2.6  构造器引用

    // 构造器引用

    @Test

    public void test5() {

       Supplier<Employee> sup = () -> new Employee();

       Employee emp = sup.get();

      

       // 构造器引用方式

       Supplier<Employee> sup1 = Employee::new;

       Employee emp1 = sup.get();

       System.out.println(emp1);

    }

   

    @Test

    public void test6() {

       Function<Integer, Employee> func = (x) -> new Employee(x);

       func.apply(20);

      

       // 需要调用的构造器的参数列表要与函数式接口中抽象方法参数列表保持一致

       Function<Integer, Employee> func2 = Employee::new;

       Employee emp1 = func2.apply(18);

       System.out.println(emp1);

      

       BiFunction<Integer, String, Employee> bf = Employee::new;

       Employee emp2 = bf.apply(20, "张三");

       System.out.println(emp2);

    }

注意:需要调用的构造器的参数列表要与函数式接口中抽象方法参数列表保持一致。

2.7  数组引用

格式:Type::new

    // 数组引用

    @Test

    public void test7() {

       Function<Integer, String[]> func = (x) -> new String[x];

       String strs[] = func.apply(10);

       System.out.println(strs.length);

      

       Function<Integer, String[]> func2 = String[]::new;

       String strs2[] = func2.apply(20);

       System.out.println(strs2.length);

    }

3、StreamAPI

3.1  什么是Stream?

是数据渠道,用于操作数据源(集合、数组)所生产的元素序列。

3.2  Stream的操作三个步骤

  1. 创建Stream

一个数据源(如:集合、数组),获取一个流

  1. 中间操作

一个中间操作链,对数据源的数据进行处理

  1. 终止操作

一个终止操作,执行中间操作链,并产生结果

3.2.1  创建Stream

/**

 * StreamAPI三个操作步骤:

 *     1、创建Stream

 *     2、中间操作

 *     3、终止操作

 */

public class TestStreamAPI1 {

    // 创建Stream

    @Test

    public void test1() {

       // 1、可以通过Conllection系列集合提供的顺序流stream()或并行流parallelStream()

       List<String> list = new ArrayList<>();

       Stream<String> stream1 = list.stream();

       stream1 = list.parallelStream();

      

       // 2、通过Arrays中的静态方法stream()获取数据流

       Integer ints[] = new Integer[10];

       Stream<Integer> stream2 = Arrays.stream(ints);

      

       // 3、通过Stream类中的静态方法of()

       Stream<String> stream3 = Stream.of("aa", "bb", "cc");

      

       String str[] = new String[10];

       Stream<String> stream4 = Stream.of(str);

      

       // 4、创建无限流-迭代

       Stream<Integer> stream5 = Stream.iterate(0, (x) -> x + 2);

       stream5.limit(10).forEach(System.out::println);

      

       // 5、创建无限流-生成

       Stream.generate(() -> Math.random())

                     .limit(5)

                     .forEach(System.out::println);

    }

}

3.2.2  Stream的中间操作

3.2.2.1  筛选和切片

filter

    List<Employee> emps = Arrays.asList(

           new Employee("张三", 18, 3333.33),

           new Employee("李四", 38, 4444.44),

           new Employee("王五", 50, 5555.55),

           new Employee("赵六", 16, 6666.66),

           new Employee("田七", 28, 7777.77)

    );

   

    // filter-接收Lambda,从流中排除某些元素

    @Test

    public void test1() {

       Stream<Employee> stream = emps.stream()

              .filter((e) -> {

                  System.out.println("StreamAPI的中间操作");

                  return e.getAge() > 35;

              });

      

       // 终止操作:一次性执行全部内容,即“惰性求值”

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

    }

limit

    // limit-截断流,使其元素不超过给定数量

    @Test

    public void test2() {

       emps.stream()

           .filter((e) -> e.getSalary() > 5000)

           .limit(2)

           .forEach(System.out::println);

    }

skip

    // skip-跳过元素,返回一个扔掉了前n个元素的流,若流中元素不足n个,则返回一个空流。

    @Test

    public void test3() {

       emps.stream()

           .filter((e) -> e.getSalary() > 5000)

           .skip(2)

           .forEach(System.out::println);

    }

distinct

    // distinct-筛选,通过流所生产元素的hashCode()和equals()去除重复元素

    @Test

    public void test4() {

       emps.stream()

           .filter((e) -> e.getSalary() > 5000)

           .distinct()

           .forEach(System.out::println);

    }

3.2.2.2  映射

map

    // map-接收Lambda,将元素转换成其他形式或提取信息。接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。

    @Test

    public void test1() {

       List<String> list = Arrays.asList("aa", "bb", "cc");

      

       list.stream()

           .map((str) -> str.toUpperCase())

           .forEach(System.out::println);

      

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

      

       emps.stream()

           .map(Employee::getName)

           .forEach(System.out::println);

    }

flatMap

    // flatMap-接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流链接成一个流。

    @Test

    public void test2() {

       List<String> list = Arrays.asList("aa", "bb", "cc");

      

       Stream<Stream<Character>> stream = list.stream()

                     .map(TestStreamAPI3::filterCharacter);// {{a, a}, {b, b}, {c, c}}

      

       stream.forEach((sm) -> {

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

       });

      

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

      

       Stream<Character> stream2 = list.stream()

              .flatMap(TestStreamAPI3::filterCharacter);// {a, a, b, b, c, c}

 

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

    }

   

    public static Stream<Character> filterCharacter(String str) {

       List<Character> list = new ArrayList<>();

      

       for (Character character : str.toCharArray()) {

           list.add(character);

       }

      

       return list.stream();

    }

3.2.2.3  排序

sorted(Comparable)-自然排序

    // sorted(Comparable)-自然排序

    @Test

    public void test1() {

       List<String> list = Arrays.asList("cc", "aa", "bb", "ee", "dd");

      

       list.stream()

           .sorted()

           .forEach(System.out::println);

    }

                           sorted(Comparator)-定制排序

    // sorted(Comparator)-定制排序

    // 需求:按年龄排序,年龄一样按姓名排序

    @Test

    public void test2() {

       emps.stream()

           .sorted((e1, e2) -> {

              if(e1.getAge().equals(e2.getAge())) {

                  return e1.getName().compareTo(e1.getName());

              }else {

                  return e1.getAge().compareTo(e2.getAge());

              }

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

    }

3.2.3  终止操作

3.2.3.1  查找与匹配

    // 查找与匹配

    @Test

    public void test1() {

       // allMatch-检查是否匹配所有元素

       boolean b1 = emps.stream()

                     .allMatch((e) -> e.getStatus().equals(Status.BUSY));

       System.out.println(b1);

      

       // anyMatch-检查是否至少匹配一个元素

       boolean b2 = emps.stream()

                     .anyMatch((e) -> e.getStatus().equals(Status.BUSY));

       System.out.println(b2);

      

       // noneMatch-检查是否没有匹配所有元素

       boolean b3 = emps.stream()

                     .noneMatch((e) -> e.getStatus().equals(Status.OTHER));

       System.out.println(b3);

      

       // findFirst-返回第一个元素

       // 需求:按工资排序,获取第一个员工信息

       Optional<Employee> op1 = emps.stream()

           .sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()))

           .findFirst();

       System.out.println(op1.get());

      

       // findAny-返回当前流中的任意元素

       // 需求:找一个空闲状态的员工,添加到开发团队中

       Optional<Employee> op2 = emps.parallelStream()// 并行流-多条线程进行,谁先找到就是谁

           .filter((e) -> e.getStatus().equals(Status.FERR))

           .findAny();

       System.out.println(op2.get());

      

        // count-返回流中元素的总个数

       Long count = emps.stream().count();

       System.out.println(count);

      

       // max-返回流中最大值

       // 需求:获取工资最高的员工信息

       Optional<Employee> op3 = emps.stream()

           .max((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));

       System.out.println(op3.get());

      

       // min-返回流中最小值

       // 需求:获取公司中工资最少员工的工资

       Optional<Double> op4 = emps.stream()

           .map(Employee::getSalary)

           .min(Double::compare);

       System.out.println(op4.get());

    }

3.2.3.2  归约

    // 归约-可以将流中元素繁复结合起来,得到一个值

    @Test

    public void test2() {

       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);// 0代表数字0,不是下标

       System.out.println(sum);

      

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

      

       // 需求:计算所有员工的工资总和

       Optional<Double> op = emps.stream()

           .map(Employee::getSalary)

           .reduce(Double::sum);

       System.out.println(op.get());

    }

3.2.3.3  收集

    // 收集-将流转换为其他形式,接收一个Collertor接口的实现,用于给Stream中元素做汇总的方法

    @Test

    public void test3() {

       // 需求:获取当前公司所有员工的姓名添加到集合中

       // List-把流中所有元素收集到List中

       List<String> list = emps.stream()

           .map(Employee::getName)

           .collect(Collectors.toList());

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

      

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

      

       // Set-把流中所有元素收集到Set中,删除重复项

       Set<String> set = emps.stream()

              .map(Employee::getName)

              .collect(Collectors.toSet());

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

      

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

      

       Set<String> hashSet = emps.stream()

              .map(Employee::getName)

              .collect(Collectors.toCollection(HashSet::new));

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

      

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

      

       // Map-把流中所有元素收集到Map中,当出现相同的key时会抛异常

       Map<String, Integer> map = emps.stream()

              .collect(Collectors.toMap(Employee::getName, Employee::getAge));

       System.out.println(map);

    }

 

    @Test

    public void test4() {

       // 员工总数

       Long count = emps.stream()

           .collect(Collectors.counting());

       System.out.println(count);

      

       // 工资平均数

       Double avg = emps.stream()

              .collect(Collectors.averagingDouble(Employee::getSalary));

       System.out.println(avg);

      

       // 工资总和

       Double sum = emps.stream()

              .collect(Collectors.summingDouble(Employee::getSalary));

       System.out.println(sum);

      

       // 工资最大值的员工

       Optional<Employee> op = emps.stream()

           .collect(Collectors.maxBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));

       System.out.println(op.get());

      

       // 工资最小值的金额

       Optional<Double> op2 = emps.stream()

              .map(Employee::getSalary)

              .collect(Collectors.minBy(Double::compare));

       System.out.println(op2.get());

      

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

      

       DoubleSummaryStatistics dss = emps.stream()

              .collect(Collectors.summarizingDouble(Employee::getSalary));

      

       System.out.println(dss.getAverage()+"  " + dss.getCount() + "  " + dss.getMax() + "  "

                         + dss.getMin() + "  " + dss.getSum());

    }

 

    @Test

    public void test5() {

       // 分组

       Map<Status, List<Employee>> map1 = emps.stream()

           .collect(Collectors.groupingBy(Employee::getStatus));

       System.out.println(map1);

      

       // 多级分组

       Map<Status, Map<String, List<Employee>>> map2 = emps.stream()

           .collect(Collectors.groupingBy(Employee::getStatus,

                  Collectors.groupingBy((e) -> {

                     if(e.getAge() <= 35) {

                         return "青年";

                     }else if(e.getAge() <= 50) {

                         return "中年";

                     }else {

                         return "老年";

                     }

                  })));

       System.out.println(map2);

 

       // 分区

       Map<Boolean, List<Employee>> map3 = emps.stream()

           .collect(Collectors.partitioningBy((e) -> e.getSalary() > 6000));

       System.out.println(map3);

      

       // 拼接

       String str = emps.stream()

              .map(Employee::getName)

              .collect(Collectors.joining(",", "**", "**"));

       System.out.println(str);

    }

注意:

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

4、并行流与顺序流

4.1  什么是并行流

并行流就是把一个内容分成多个数据块,并用不同的线程分别处理每个数据块的流。

4.2  了解Fork/Join框架

就是在必要的情况下,将一个大任务,进行拆分(fork)成若干个小任务,再将一个个的小任务运算的结果进行汇总(join)。

4.3  使用Fork/Join框架

ForkJoinCalulate.java

/**

 * 累加运算测试

 */

public class ForkJoinCalulate extends RecursiveTask<Long> {

 

    /**

     *

     */

    private static final long serialVersionUID = 6262874164889171856L;

   

    private long start;

    private long end;

   

    private static final long THRESHOLE = 10000L;// 临界值

 

    @Override

    protected Long compute() {

       long length = end - start;

      

       if(length <= THRESHOLE) {

           long sum = 0L;

          

           for (long i = start; i <= end; i++) {

              sum += i;

           }

          

           return sum;

       }else {

           long middle = (start + end) / 2;

          

           ForkJoinCalulate left = new ForkJoinCalulate(start, middle);

           left.fork();// 拆分子任务,同时压入线程队列

          

           ForkJoinCalulate right = new ForkJoinCalulate(middle + 1, end);

           right.fork();// 拆分子任务,同时压入线程队列

          

           return left.join() + right.join();

       }

    }

   

    public ForkJoinCalulate() {

    }

 

    public ForkJoinCalulate(long start, long end) {

       this.start = start;

       this.end = end;

    }

   

}

TestForkJoin.java

public class TestForkJoin {

    /*

     * ForkJoin框架-数据较大使用比较好,数据越大效率越高

     */

    @Test

    public void test1() {

       Instant start = Instant.now();

      

       ForkJoinPool pool = new ForkJoinPool();

      

       ForkJoinTask<Long> task = new ForkJoinCalulate(0, 10000000000L);

       Long sum = pool.invoke(task);

      

       Instant end = Instant.now();

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

    }

   

    /*

     * 普通for-数据小使用比较好,省去了拆分的时间

     */

    @Test

    public void test2() {

       Instant start = Instant.now();

       long sum = 0L;

      

       for (long i = 0; i <= 10000000000L; i++) {

           sum += i;

       }

      

       Instant end = Instant.now();

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

    }

}

4.4  顺序流

    /*

     * 顺序流

     */

    @Test

    public void test3() {

       LongStream.rangeClosed(0, 10000000000L)

           .sequential()// 顺序流

           .reduce(0, Long::sum);

    }

4.5  并行流

    /*

     * 并行流

     */

    @Test

    public void test4() {

       LongStream.rangeClosed(0, 10000000000L)

           .parallel()// 并行流

           .reduce(0, Long::sum);

    }

5、Optional类

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

5.1  Optional容器类的常用方法

public class TestOptional {

 

    /*

     * Optional容器类的常用方法:

     * of(T value):创建一个Optional实例

     */

    @Test

    public void test1() {

       Optional<Employee> op = Optional.of(new Employee());

       System.out.println(op.get());

    }

   

    /*

     * empty():创建一个空的Optional实例

     */

    @Test

    public void test2() {

       Optional<Employee> op = Optional.empty();

       System.out.println(op.get());

    }

   

    /*

     * ofNullable(T value):若T不为null,创建Optional实例,否则创建空实例

     * isPresent():判断是否包含值

     * orElse(T other):如果调用对象包含值,返回该值,否则返回other

     * orElseGet(T other):如果调用对象包含值,返回该值,否则返回other获取的值

     */

    @Test

    public void test3() {

       Optional<Employee> op = Optional.ofNullable(null);

//     System.out.println(op.get());

      

       System.out.println(op.isPresent());

      

       Employee emp = op.orElse(new Employee("张三", 18, 333.33));

       System.out.println(emp);

      

       Employee emp1 = op.orElseGet(() -> new Employee());

       System.out.println(emp1);

    }

   

    /*

     * map(Function mapper):如果有值对其处理,并返回处理后的Optional,否则返回Optional.empty()

     * flatMap(Function mapper):与map类似,要求返回值必须是Optional

     */

    @Test

    public void test4() {

       Optional<Employee> op = Optional.ofNullable(new Employee("张三", 18, 333.33));

       Optional<String> str = op.map((e) -> e.getName());

       System.out.println(str.get());

      

       Optional<String> str1 = op.flatMap((e) -> Optional.of(e.getName()));

       System.out.println(str1.get());

    }

   

}

6、接口中的默认方法与静态方法

6.1  什么是默认方法?

Java8中接口允许声明具有实现的方法,叫做默认方法。

6.2  类优先原则

若一个接口中定义了一个默认方法,而另外一个父类中又定义了一个同名的方法时,选择父类中的方法。如果一个父类提供了调用方法具体的实现,那么接口中具有相同名称和参数的默认方法会被忽略。

6.3  接口冲突

如果一个接口提供了一个默认方法,而另一个接口也提供了一个具有相同名称和参数列表的方法,那么必须覆盖方法来解决冲突。

    1.  Java8中接口允许声明静态方法

7、新时间日期API

7.1  线程安全问题

案例:解决了传统时间格式化的线程安全问题。每次都产生新的对象实例。

    @Test

    public void test2() throws InterruptedException, ExecutionException {

       DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");

      

       Callable<LocalDate> task = () -> LocalDate.parse("20180815", dtf);

      

       

       ExecutorService pool = Executors.newFixedThreadPool(10);

      

       List<Future<LocalDate>> results = new ArrayList<>();

      

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

           results.add(pool.submit(task));

       }

      

       for (Future<LocalDate> future : results) {

           System.out.println(future.get());

       }

      

       pool.shutdown();

    }

7.2  ISO-8601日历系统

    /*

     * 1、ISO-8601日历系统:国际标准化组织制定的现代公民日期和时间的表示法

     */

    @Test

    public void test1() {

       LocalDateTime ldt = LocalDateTime.now();

       System.out.println(ldt);

      

       LocalDateTime ldt2 = LocalDateTime.of(2008, 8, 8, 8, 8, 8, 888000000);

       System.out.println(ldt2);

      

       LocalDateTime ldt3 = ldt.plusYears(2);

       System.out.println(ldt3);

      

       LocalDateTime ldt4 = ldt.minusYears(2);

       System.out.println(ldt4);

      

       System.out.println(ldt.getYear());

       System.out.println(ldt.getMonthValue());

       System.out.println(ldt.getDayOfMonth());

       System.out.println(ldt.getHour());

       System.out.println(ldt.getMinute());

       System.out.println(ldt.getSecond());

       System.out.println(ldt.getNano());

    }

7.3  时间戳

    /*

     * 2、时间戳:以Unix元年:1970年1月1日 00:00:00 至目前时间之间的毫秒值

     */

    @Test

    public void test2() {

       Instant ins1 = Instant.now();

       System.out.println(ins1);// 默认获取UTC时间,协调世界时

      

       OffsetDateTime odt = ins1.atOffset(ZoneOffset.ofHours(8));

       System.out.println(odt);

      

       // 操作时间戳

       System.out.println(ins1.toEpochMilli());

      

       Instant ins2 = Instant.ofEpochSecond(60);

       System.out.println(ins2);

    }

   

    /*

     * 3、Duration:计算两个时间之间的间隔

     */

    @Test

    public void test3() {

       Instant ins1 = Instant.now();

      

       try {

           Thread.sleep(2000);

       } catch (InterruptedException e) {

           e.printStackTrace();

       }

      

       Instant ins2 = Instant.now();

      

       Duration dura = Duration.between(ins1, ins2);

       System.out.println(dura.toMillis());

      

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

      

       LocalTime lt1 = LocalTime.now();

      

       try {

           Thread.sleep(2000);

       } catch (InterruptedException e) {

           e.printStackTrace();

       }

      

       LocalTime lt2 = LocalTime.now();

      

       Duration dura2 = Duration.between(lt1, lt2);

       System.out.println(dura2.toMillis());

    }

   

    /*

     * 4、Period:计算两个日期之间的间隔

     */

    @Test

    public void test4() {

       LocalDate ld1 = LocalDate.of(2015, 2, 2);

       LocalDate ld2 = LocalDate.now();

      

       Period period = Period.between(ld1, ld2);

       System.out.println(period);

      

       System.out.println("相差" + period.getYears() + "年"

              + period.getMonths() + "月"

              + period.getDays() + "天");

    }

7.4  时间校正器

    /*

     * 时间校正器:TemporalAdjuster

     */

    @Test

    public void test5() {

       LocalDateTime ldt = LocalDateTime.now();

       System.out.println(ldt);

      

       LocalDateTime ldt2 = ldt.withDayOfMonth(10);

       System.out.println(ldt2);

      

       LocalDateTime ldt3 = ldt.with(TemporalAdjusters.next(DayOfWeek.SATURDAY));

       System.out.println(ldt3);

    }

7.5  格式化日期/时间

    /*

     * 格式化日期/时间

     */

    @Test

    public void test6() {

       DateTimeFormatter dtf = DateTimeFormatter.ISO_DATE;

       LocalDateTime ldt = LocalDateTime.now();

      

       String strDate = ldt.format(dtf);

       System.out.println(strDate);

      

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

      

       DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");

       String strDate2 = dtf2.format(ldt);

       System.out.println(strDate2);

      

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

      

       LocalDateTime newDate = ldt.parse(strDate2, dtf2);

       System.out.println(newDate);

    }

7.6  时区的处理

    /*

     * 时区的处理

     */

    @Test

    public void test7() {

//     Set<String> set = ZoneId.getAvailableZoneIds();

//     set.forEach(System.out::println);// Europe/Dublin

      

       LocalDateTime ldt = LocalDateTime.now(ZoneId.of("Europe/Dublin"));

       System.out.println(ldt);

      

       LocalDateTime ldt2 = LocalDateTime.now(ZoneId.of("Europe/Dublin"));

       ZonedDateTime zdt = ldt2.atZone(ZoneId.of("Europe/Dublin"));

      

       System.out.println(zdt);

    }

8、重复注解与类型注解

public class TestAnnotation {

   

    // 配合一些框架去使用

    private /*@Notnull*/ Object obj = null;

 

    @Test

    public void test1() throws NoSuchMethodException, SecurityException {

       Class<TestAnnotation> clazz = TestAnnotation.class;

       Method m = clazz.getMethod("show");

      

       MyAnnotation[] mas = m.getAnnotationsByType(MyAnnotation.class);

      

       for (MyAnnotation myAnnotation : mas) {

           System.out.println(myAnnotation.value());

       }

    }

   

    @MyAnnotation("Hello")

    @MyAnnotation("World")

    public void show(@MyAnnotation("param")String str) {

      

    }

}

 

猜你喜欢

转载自blog.csdn.net/Jackie_ZHF/article/details/85243621