Java8 新特性学习总结 - Go语言中文社区

Java8 新特性学习总结


Lambda 表达式

Lambda 是一个匿名函数,我们可以把 Lambda 表达式理解为是一段可以传递的代码(将代码像数据一样进行传递)。可以写出更简洁、更灵活的代码。作为一种更紧凑的代码风格,使Java的语言表达能力得到了提升。
Lambda 表达式在Java 语言中引入了一个新的语法元素和操作符。这个操作符为 “->” , 该操作符被称为 Lambda 操作符或箭头操作符。它将 Lambda 分为两个部分:
- 左侧:指定了 Lambda 表达式需要的所有参数
- 右侧:指定了 Lambda 体,即 Lambda 表达式要执行的功能。

Lambda 表达式语法

语法格式一:无参,无返回值,Lambda 体只需一条语句

Runnable runnable = () -> System.out.println("hello Lambda");

语法格式二:Lambda 需要一个参数

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

语法格式三:Lambda 只需要一个参数时,参数的小括号可以省略

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

语法格式四:Lambda 需要两个参数,并且有返回值

Comparator<Integer> comparator = (x,y) -> {
        System.out.println("相加结果是:"+(x+y));
        return Integer.compare(x,y);
    };

语法格式五:当 Lambda 体只有一条语句时,return 与大括号可以省略

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

语法格式六:数据类型可以省略,因为可由编译器推断得出,称为“类型推断”

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

类型推断

上述 Lambda 表达式中的参数类型都是由编译器推断得出的。Lambda 表达式中无需指定类型,程序依然可以编译,这是因为 javac 根据程序的上下文,在后台推断出了参数的类型。Lambda 表达式的类型依赖于上下文环境,是由编译器推断出来的。这就是所谓的“类型推断”。

    /**
     * Lambda表达式基础语法,Java8中引入新的操作符"->"
     * Lambda表达式分为左右两部分:
     *  左:Lambda表达式的参数列表
     *  右:Lambda表达式中所需执行的功能,即Lambda体
     */
    public class LambdaDemo {

        @Test
        public void test1(){
            Runnable r = new Runnable() {

                @Override
                public void run() {
                    System.out.println("hello world");
                }
            };
            r.run();
            System.out.println("------------");

            //Lambda表达式
            Runnable runnable = () -> System.out.println("hello Lambda");
            runnable.run();
        }

        @Test
        public void test2(){
            Consumer<String> consumer = new Consumer<String>() {

                @Override
                public void accept(String t) {
                    System.out.println(t);
                }
            };
            consumer.accept("hello consumer !");
            System.out.println("---------------");

            //Lambda表达式
    //      Consumer<String> con = (t) -> System.out.println(t);
            Consumer<String> con = t -> System.out.println(t);
            con.accept("hello Lambda !");
        }

        @Test
        public void test3(){
            Comparator<Integer> comparator = (x,y) -> {
                System.out.println("相加结果是:"+(x+y));
                return Integer.compare(x,y);
            };

            int compare = comparator.compare(1, 2);
            System.out.println(compare);
        }

        @Test
        public void test4(){
            Comparator<Integer> comparator = (x,y) -> Integer.compare(x,y);

            int compare = comparator.compare(1, 2);
            System.out.println(compare);
        }

        @Test
        public void test5(){
            show(new HashMap<>());
        }

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

        }
    }

函数式接口

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

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

    /**
     * 函数式接口
     */
    public class TestFunction {

        //Consumer<T>消费型接口
        @Test
        public void test1(){
            cost(8888, (m) -> System.out.println("共消费:" + m + "元"));
        }

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

        //Supplier<T> 供给型接口
        @Test
        public void test2(){
            List<Integer> list = getNumList(8, () -> (int)(Math.random() * 100));
            for (Integer integer : list) {
                System.out.println(integer);
            }
        }

        //产生指定数量的整数,放入集合中
        public List<Integer> getNumList(int num,Supplier<Integer> sup){
            List<Integer> list = new ArrayList<Integer>();

            for (int i = 0; i < num; i++) {
                Integer n = sup.get();
                list.add(n);
            }

            return list;
        }

        //Function<T,R> 函数型接口
        @Test
        public void test3(){
            String string = strHandler(" 函数型接口测试 ", (str) -> str.trim().substring(0, 5));
            System.out.println(string);
        }

        //用于处理字符串
        public String strHandler(String str,Function<String, String> fun){
            return fun.apply(str);
        }

        //Predicate<T> 断言型接口
        @Test
        public void test4(){
            List<String> list = Arrays.asList("hello","Lambda","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 str : list) {
                if (pre.test(str)) {
                    strList.add(str);
                }
            }
            return strList;
        }
    }

其他接口

方法引用与构造器引用

方法引用

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

如下三种主要使用情况:
- 对象::实例方法
- 类::静态方法
- 类::实例方法

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

构造器引用

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

数组引用

格式: type[] :: new

    /**
     * 方法引用:若Lambda 体中的内容有方法已经实现了,我们可以使用"方法引用"
     */
    public class TestMethodRef {

        @Test
        public void test1(){
            Consumer<String> con = (x) -> System.out.println(x);
            con.accept("shuai");

            //方法引用,对象::实例方法名
            Consumer<String> consumer = System.out::println;
            consumer.accept("test");
        }

        @Test
        public void test2(){
            Person person = new Person();
            Supplier<String> supplier = () -> person.getName();
            String str = supplier.get();
            System.err.println(str);

            //方法引用,对象::实例方法名
            Supplier<Integer> sup = person::getAge;
            Integer age = sup.get();
            System.out.println(age);
        }

        //类::静态方法名
        @Test
        public void test3(){
            Comparator<Integer> com = (x,y) -> Integer.compare(x, y);
            //使用前提,compare的参数和返回值与Comparator一致
            Comparator<Integer> comparator = Integer :: compare;
        }

        //类::实例方法名
        @Test
        public void test4(){
            BiPredicate<String, String> bp = (x,y) -> x.equals(y);
            //使用条件:第一个参数是实例方法调用者,第二个参数是实例方法的参数
            BiPredicate<String, String> biPredicate = String :: equals;
        }

        //构造器引用
        @Test
        public void test5(){
            Supplier<Person> sup = () -> new Person();

            //构造器引用方式
            Supplier<Person> supplier = Person :: new;
            Person person = supplier.get();
            System.out.println(person);
        }

        //构造器引用
        @Test
        public void test6(){
            Function<Integer, Person> fun = (x) -> new Person(x);

            Function<Integer, Person> function = Person :: new;
            Person person = function.apply(2);
            System.out.println(person);
            System.out.println("--------------------");

            BiFunction<String, Integer, Person> biFunction = Person :: new;
            Person person2 = biFunction.apply("张三", 23);
            System.out.println(person2);
        }

        //数组引用
        @Test
        public void test7(){
            Function<Integer, String[]> fun = (x) -> new String[x]; 
            String[] strs = fun.apply(8);
            System.out.println(strs.length);

            Function<Integer, String[]> function = String[] :: new;
            String[] strArray = function.apply(6);
            System.out.println(strArray.length);
        }
    }

Stream API

Stream 是 Java8 中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。使用Stream API 对集合数据进行操作,就类似于使用 SQL 执行的数据库查询。也可以使用 Stream API 来并行执行操作。简而言之,Stream API 提供了一种高效且易于使用的处理数据的方式。

Stream

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

Stream 的操作三个步骤

  • 创建 Stream
    一个数据源(如:集合、数组),获取一个流
  • 中间操作
    一个中间操作链,对数据源的数据进行处理
  • 终止操作(终端操作)
    一个终止操作,执行中间操作链,并产生结果

创建 Stream

Java8 中的 Collection 接口被扩展,提供了两个获取流的方法:
- default Stream stream() : 返回一个顺序流
- default Stream parallelStream() : 返回一个并行流

Java8 中的 Arrays 的静态方法 stream() 可以获取数组流:
- static Stream stream(T[] array): 返回一个流

可以使用静态方法 Stream.of(), 通过显示值创建一个流。它可以接收任意数量的参数。
- public static Stream of(T… values) : 返回一个流

可以使用静态方法 Stream.iterate() 和Stream.generate(), 创建无限流。
- 迭代
public static Stream iterate(final T seed, final UnaryOperator f)
- 生成
public static Stream generate(Supplier s) :

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

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

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

        //4.创建无限流
        //迭代
        Stream<Integer> stream4 = Stream.iterate(0, (x) -> x + 2);
        stream4.limit(8).forEach(System.out :: println);

        //生成
        Stream.generate(() -> Math.random()).limit(6)
            .forEach(System.out :: println);
    }       

Stream 的中间操作

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

筛选与切片

映射

排序

    /**
     * Stream API的中间操作
     */
    public class TestSteamAPI2 {

        List<Person> persons = Arrays.asList(
                new Person(2, "钱四", 24),
                new Person(1, "张三", 33),
                new Person(2, "李四", 24),
                new Person(3, "王五", 65),
                new Person(4, "赵六", 26),
                new Person(4, "赵六", 26),
                new Person(5, "陈七", 27)
        );

        //内部迭代,由Stream API完成
        @Test
        public void test1(){
            //中间操作,不会执行任何操作
            Stream<Person> stream = persons.stream()
                                        .filter((e) -> {
                                            System.out.println("Stream的中间操作");
                                            return e.getAge() > 25;
                                        });
            //终止操作,一次性执行全部内容,即"惰性求值"
            stream.forEach(System.out :: println);
        }

        //外部迭代
        @Test
        public void test2(){
            Iterator<Person> iterator = persons.iterator();
            while (iterator.hasNext()) {
                System.out.println(iterator.next());
            }
        }

        //limit,截断
        @Test
        public void test3(){
            persons.stream()
                .filter((e) -> {
                    System.out.println("迭代操作"); //短路
                    return e.getAge() > 24;
                })
                .limit(2)
                .forEach(System.out :: println);
        }

        //跳过skip,distinct去重(要重写equals和hashcode)
        @Test
        public void test4(){
            persons.stream()
                    .filter((e) -> e.getAge() > 23)
                    .skip(2)
                    .distinct()
                    .forEach(System.out :: println);
        }

        //映射
        @Test
        public void test5(){
            List<String> list = Arrays.asList("a","bb","c","d","e");

            list.stream().map((str) -> str.toUpperCase())
                .forEach(System.out :: println);
            System.out.println("---------------");

            persons.stream().map((Person :: getName)).forEach(System.out :: println);
            System.out.println("---------------");

            Stream<Stream<Character>> stream = list.stream()
                .map(TestSteamAPI2 :: filterCharacter);

            stream.forEach((s) -> {
                s.forEach(System.out :: println);
            });
            System.out.println("-----------------");

            //flatMap
            Stream<Character> stream2 = list.stream()
                .flatMap(TestSteamAPI2 :: filterCharacter);
            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();
        }

        //排序
        @Test
        public void test6(){
            List<String> list = Arrays.asList("bb","c","aa","ee","ddd");

            list.stream()
                .sorted() //自然排序
                .forEach(System.out :: println);
            System.out.println("------------");

            persons.stream()
                    .sorted((p1,p2) -> {
                        if (p1.getAge() == p2.getAge()) {
                            return p1.getName().compareTo(p2.getName());
                        } else {
                            return p1.getAge() - p2.getAge();
                        }
                    }).forEach(System.out :: println);

        }

    }

Stream 的终止操作

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

查找与匹配

归约



map 和 reduce 的连接通常称为 map-reduce 模式。

收集


Collector 接口中方法的实现决定了如何对流执行收集操作(如收集到 List、Set、Map)。但是 Collectors 实用类提供了很多静态方法,可以方便地创建常见收集器实例。

    /**
     * Stream API的终止操作
     */
    public class TestSteamAPI3 {

        List<Person> persons = Arrays.asList(
                new Person(2, "钱四", 24,Status.YOUNG),
                new Person(1, "张三", 23,Status.YOUNG),
                new Person(2, "李四", 24,Status.YOUNG),
                new Person(3, "王五", 65,Status.OLD),
                new Person(4, "赵六", 26,Status.MIDDLE),
                new Person(4, "赵六", 56,Status.OLD),
                new Person(5, "陈七", 27,Status.MIDDLE)
        );

        //查找与匹配
        @Test
        public void test1(){
            boolean b = persons.stream()
                                .allMatch((e) -> e.getStatus().equals(Status.YOUNG));
            System.out.println(b);

            boolean b2 = persons.stream()
                    .anyMatch((e) -> e.getStatus().equals(Status.YOUNG));
            System.out.println(b2);

            boolean b3 = persons.stream()
                    .noneMatch((e) -> e.getStatus().equals(Status.MIDDLE));
            System.out.println(b3);

            Optional<Person> op = persons.stream()
                    .sorted((e1,e2) -> Integer.compare(e1.getAge(), e2.getAge()))
                    .findFirst();
            System.out.println(op.get());

            Optional<Person> optional = persons.stream()
                    .filter((e) -> e.getStatus().equals(Status.OLD))
                    .findAny();
            System.out.println(optional.get());
        }

        //最大,最小
        @Test
        public void test2(){
            long count = persons.stream()
                    .count();
            System.out.println(count);

            Optional<Person> optional = persons.stream()
                    .max((e1,e2) -> Integer.compare(e1.getId(), e2.getId()));
            System.out.println(optional.get());

            Optional<Integer> op = persons.stream()
                    .map(Person :: getAge)
                    .min(Integer :: compare);
            System.out.println(op.get());
        }

        //归约
        @Test
        public void test3(){
            List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8);

            Integer sum = list.stream()
                .reduce(0, (x,y) -> x + y);
            System.out.println(sum);
            System.out.println("------------");

            Optional<Integer> optional = persons.stream()
                    .map(Person :: getAge)
                    .reduce(Integer :: sum);
            System.out.println(optional.get());
        }

        //收集
        @Test
        public void test4(){
            List<String> list = persons.stream()
                    .map(Person :: getName)
                    .collect(Collectors.toList());
            list.forEach(System.out :: println);
            System.out.println("------------");

            Set<String> set = persons.stream()
                    .map(Person :: getName)
                    .collect(Collectors.toSet());
            set.forEach(System.out :: println);
            System.out.println("------------");

            HashSet<String> hashSet = persons.stream()
                    .map(Person :: getName)
                    .collect(Collectors.toCollection(HashSet :: new));
            hashSet.forEach(System.out :: println);
        }

        @Test
        public void test5(){
            Long count = persons.stream()
                    .collect(Collectors.counting());
            System.out.println("总人数="+count);
            System.out.println("----------------");

            //平均值
            Double avg = persons.stream()
                    .collect(Collectors.averagingInt(Person :: getAge));
            System.out.println("平均年龄="+avg);
            System.out.println("---------------");

            //总和
            Integer sum = persons.stream()
                    .collect(Collectors.summingInt(Person :: getAge));
            System.out.println("年龄总和="+sum);
            System.out.println("----------------");

            //最大值
            Optional<Person> max = persons.stream()
                    .collect(Collectors.maxBy((e1,e2) -> Integer.compare(e1.getAge(), e2.getAge())));
            System.out.println("最大年龄是"+max.get());
            System.out.println("----------------");

            //最小值
            Optional<Person> min = persons.stream()
                    .collect(Collectors.minBy((e1,e2) -> Integer.compare(e1.getAge(), e2.getAge())));
            System.out.println("最小年龄是"+min.get());
        }

        //分组
        @Test
        public void test6(){
            Map<Status, List<Person>> map = persons.stream()
                    .collect(Collectors.groupingBy(Person :: getStatus));//根据年龄层分组
            System.out.println(map);
        }

        //多级分组
        @Test
        public void test7(){
            Map<Status, Map<String, List<Person>>> map = persons.stream()
                    .collect(Collectors.groupingBy(Person :: getStatus ,Collectors.groupingBy((e) -> {
                        if (e.getId()%2 == 1) {
                            return "单号";
                        } else {
                            return "双号";
                        } 
                    })));
            System.out.println(map);
        }

        //分区
        @Test
        public void test8(){
            Map<Boolean, List<Person>> map = persons.stream()
                    .collect(Collectors.partitioningBy((e) -> e.getAge() > 30));
            System.out.println(map);
        }

        //IntSummaryStatistics
        @Test
        public void test9(){
            IntSummaryStatistics iss = persons.stream()
                    .collect(Collectors.summarizingInt(Person :: getAge));
            System.out.println(iss.getSum());
            System.out.println(iss.getAverage());
            System.out.println(iss.getMax());
        }

        @Test
        public void test10(){
            String str = persons.stream()
                    .map(Person :: getName)
                    .collect(Collectors.joining(",","人员名单:","等"));
            System.out.println(str);
        }
    }

并行流与串行流

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

    /**
     * FrokJoin框架
     */
    public class ForkJoinCalculate extends RecursiveTask<Long>{
        private static final long serialVersionUID = 1L;

        private long start;
        private long end;

        private static final long THRESHOLD = 10000;

        public ForkJoinCalculate() {

        }

        public ForkJoinCalculate(long start, long end) {
            this.start = start;
            this.end = end;
        }


        @Override
        protected Long compute() {
            long length = end - start ;
            if (length <= THRESHOLD) {
                long sum = 0;
                for (long i = start; i <= end; i++) {
                    sum += i;
                }
                return sum;
            }else {
                long middle = (start + end) / 2; 
                ForkJoinCalculate left = new ForkJoinCalculate();
                left.fork();//拆分子任务,同时压入线程队列

                ForkJoinCalculate right = new ForkJoinCalculate();
                right.fork();
                return left.join() + right.join();
            }
        }

    }

测试并行流

    public class TestForkJoin {

        /**
         * FrokJoin框架
         */
        @Test
        public void test1(){
            Instant start = Instant.now();

            ForkJoinPool pool = new ForkJoinPool();
            ForkJoinTask<Long> task = new ForkJoinCalculate(0,10000000000L);
            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 = 0L;

            for (long i = 0; i <= 10000000000L; 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();
            LongStream.rangeClosed(0, 10000000000L)
                        .parallel()
                        .reduce(0,Long :: sum);
            Instant end = Instant.now();
            System.out.println(Duration.between(start, end).toMillis());
        }
    }

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

接口中的默认方法

Java 8中允许接口中包含具有具体实现的方法,该方法称为“默认方法”,默认方法使用 default 关键字修饰。
接口默认方法的”类优先”原则
若一个接口中定义了一个默认方法,而另外一个父类或接口中又定义了一个同名的方法时
- 选择父类中的方法。如果一个父类提供了具体的实现,那么接口中具有相同名称和参数的默认方法会被忽略。
- 接口冲突。如果一个父接口提供一个默认方法,而另一个接口也提供了一个具有相同名称和参数列表的方法(不管方法是否是默认方法),那么必须覆盖该方法来解决冲突。

接口中的静态方法

Java8 中,接口中允许添加静态方法。

    public interface MyInterface {

        default String getName(){
            return "接口测试";
        }

        public static void show(){
            System.out.println("接口中的静态方法");
        }
    }

新时间日期 API

LocalDate、LocalTime、LocalDateTime

LocalDate、LocalTime、LocalDateTime 类的实例是不可变的对象,分别表示使用 ISO-8601日历系统的日期、时间、日期和时间。它们提供了简单的日期或时间,并不包含当前的时间信息。也不包含与时区相关的信息。

传统写法:

    public class DateFormatThreadLocal {

        private static final ThreadLocal<DateFormat> tl = new ThreadLocal<DateFormat>(){
            protected DateFormat initialValue() {
                return new SimpleDateFormat("yyyyMMdd");
            }
        };

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

    public static void main(String[] args) throws InterruptedException, ExecutionException {
//      SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

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

            @Override
            public Date call() throws Exception {
//              return sdf.parse("20170521");
                return DateFormatThreadLocal.convert("20170521");
            }

        };
        ExecutorService pool = Executors.newFixedThreadPool(10);
        List<Future<Date>> results = new ArrayList<>();
        for (int i = 0; i < 8; i++) {
            results.add(pool.submit(callable));
        }
        for (Future<Date> future : results) {
            System.out.println(future.get());
        }

        //关闭资源
        pool.shutdown();
    }

新特性:

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
        Callable<LocalDate> callable = new Callable<LocalDate>() {

            @Override
            public LocalDate call() throws Exception {
                return LocalDate.parse("20170521",dtf);
            }

        };
        ExecutorService pool = Executors.newFixedThreadPool(10);
        List<Future<LocalDate>> results = new ArrayList<>();
        for (int i = 0; i < 8; i++) {
            results.add(pool.submit(callable));
        }
        for (Future<LocalDate> future : results) {
            System.out.println(future.get());
        }

        //关闭资源
        pool.shutdown();
}

LocalDate LocalTime LocalDateTime

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

        LocalDateTime ldt2 = LocalDateTime.of(2017, 05, 21, 21, 43, 55, 33);
        System.out.println(ldt2);

        LocalDateTime ldt3 = ldt.plusYears(3);
        System.out.println(ldt3);

        LocalDateTime ldt4 = ldt.minusMonths(5);
        System.out.println(ldt4);
    }

Instant 时间戳

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

    //2.Instant
    @Test
    public void test2(){
        Instant now = Instant.now();
        System.out.println(now);

        OffsetDateTime atOffset = now.atOffset(ZoneOffset.ofHours(6));
        System.out.println(atOffset);

        Instant ins = Instant.ofEpochSecond(60);
        System.out.println(ins);
    }

Duration 和 Period

  • Duration:用于计算两个“时间”间隔
  • Period:用于计算两个“日期”间隔

    //3.Duration 
    @Test
    public void test3(){
        Instant now = Instant.now();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Instant now2 = Instant.now();
        //计算时间差
        Duration duration = Duration.between(now, now2);
        System.out.println(duration.getSeconds());
        System.out.println("----------------");
    
        LocalTime lt1 = LocalTime.now();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        LocalTime lt2 = LocalTime.now();
        System.out.println(Duration.between(lt1, lt2).toMillis());
    }
    
    //4.Period
    @Test
    public void test4(){
        LocalDate ld1 = LocalDate.of(2017, 1, 1);
        LocalDate ld2 = LocalDate.now();
        Period period = Period.between(ld1, ld2);
        System.out.println(period.getYears());
        System.out.println(period.getMonths());
        System.out.println(period.getDays());
    }
    

日期的操作

  • TemporalAdjuster : 时间校正器。有时我们可能需要获取例如:将日期调整到“下个周日”等操作。
  • TemporalAdjusters : 该类通过静态方法提供了大量的常用 TemporalAdjuster 的实现。

    //5.TemporalAdjuster:时间校正器
    @Test
    public void test5(){
        LocalDateTime ldt = LocalDateTime.now();
        System.out.println(ldt);
    
        LocalDateTime ldt2 = ldt.withDayOfMonth(8);
        System.out.println(ldt2);
    
        LocalDateTime ldt3 = ldt.with(TemporalAdjusters.next(DayOfWeek.SATURDAY));
        System.out.println(ldt3);
    
        //自定义
        LocalDateTime ldt5 =  ldt.with((l) -> {
            LocalDateTime ldt4 = (LocalDateTime) l;
            DayOfWeek dow = ldt4.getDayOfWeek();
            if (dow.equals(DayOfWeek.FRIDAY)) {
                return ldt4.plusDays(3);
            }else if (dow.equals(DayOfWeek.SATURDAY)) {
                return ldt4.plusDays(2);
            } else {
                return ldt4.plusDays(1);
            }
        });
        //下个工作日
        System.out.println(ldt5);
    }
    

解析与格式化

java.time.format.DateTimeFormatter 类
该类提供了三种格式化方法:
- 预定义的标准格式
- 语言环境相关的格式
- 自定义的格式

    //DateTimeFormatter:格式化时间/日期
    @Test
    public void test6(){
        DateTimeFormatter dtf = DateTimeFormatter.ISO_DATE_TIME;
        LocalDateTime ldt = LocalDateTime.now();

        System.out.println(ldt);
        String format = ldt.format(dtf);
        System.out.println(format);
        System.out.println("------------");
        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
        String format2 = dtf2.format(ldt);
        System.out.println(format2);

        LocalDateTime ldt2 = ldt.parse(format2,dtf2);
        System.out.println(ldt2);
    }

时区的处理

Java8 中加入了对时区的支持,带时区的时间为分别为:
ZonedDate、ZonedTime、ZonedDateTime
其中每个时区都对应着 ID,地区ID都为 “{区域}/{城市}”的格式
例如 :Asia/Shanghai 等
ZoneId:该类中包含了所有的时区信息
- getAvailableZoneIds() : 可以获取所有时区时区信息
- of(id) : 用指定的时区信息获取 ZoneId 对象

    //ZonedDate ZoneTime ZoneDateTime
    @Test
    public void test7(){
        LocalDateTime ldt = LocalDateTime.now(ZoneId.of("Europe/Tallinn"));
        System.out.println(ldt);

        LocalDateTime ldt2 = LocalDateTime.now(ZoneId.of("Europe/Tallinn"));
        ZonedDateTime zdt = ldt2.atZone(ZoneId.of("Asia/Shanghai"));
        System.out.println(zdt);
    }

与传统日期处理的转换

其他新特性

HashMap

HashMap:减少碰撞,位置相同时,条件达到链表上超过8个,总数超过64个时,数据结构改为红黑树。

ConcurrentHashMap:取消锁分段,与HashMap相同,达到条件时,数据结构改为红黑树。

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

    /**
     * Optional类
     */
    public class TestOptional {

        @Test
        public void test1(){
            //参数不能为空
            Optional<Person> op = Optional.of(new Person());

            Person person = op.get();
            System.out.println(person);
        }

        @Test
        public void test2(){
            //构建空optional
            Optional<Person> op = Optional.empty();
            System.out.println(op.get());
        }

        @Test
        public void test3(){
            //如果为null,调用empty,如果不为null,调用of
            Optional<Person> op = Optional.ofNullable(null);
    //      Optional<Person> op = Optional.ofNullable(new Person());
            if (op.isPresent()) {
                System.out.println(op.get());
            }

            //有值就用值,没值就替代
            Person person = op.orElse(new Person("张三", 23));
            System.out.println(person);
        }
    }

重复注解与类型注解

Java 8对注解处理提供了两点改进:可重复的注解及可用于类型的注解。

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

        MyAnnotation[] value();
    }

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

        String value() default "aric";
    }

    /**
     * 重复注解与类型注解
     */
    public class TestAnnotation {

        @MyAnnotation("hello")
        @MyAnnotation("test")
        public void show(@MyAnnotation("a") String str){
            System.out.println(str);
        }
    }
版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/shuaicihai/article/details/72615495
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-02-02 19:12:47
  • 阅读 ( 909 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢