博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Java8 新特性学习

Posted on 2018-09-04 19:12  激流勇进、  阅读(416)  评论(0编辑  收藏  举报

摘自:https://blog.csdn.net/shuaicihai/article/details/72615495

Lambda 表达式

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

Lambda 表达式语法

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

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

 

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

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

 

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

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

 

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

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

 

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

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

 

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

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

 

类型推断

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

   
 1  /**
 2      * Lambda表达式基础语法,Java8中引入新的操作符"->"
 3      * Lambda表达式分为左右两部分:
 4      *  左:Lambda表达式的参数列表
 5      *  右:Lambda表达式中所需执行的功能,即Lambda体
 6      */
 7     public class LambdaDemo {
 8 
 9         @Test
10         public void test1(){
11             Runnable r = new Runnable() {
12 
13                 @Override
14                 public void run() {
15                     System.out.println("hello world");
16                 }
17             };
18             r.run();
19             System.out.println("------------");
20 
21             //Lambda表达式
22             Runnable runnable = () -> System.out.println("hello Lambda");
23             runnable.run();
24         }
25 
26         @Test
27         public void test2(){
28             Consumer<String> consumer = new Consumer<String>() {
29 
30                 @Override
31                 public void accept(String t) {
32                     System.out.println(t);
33                 }
34             };
35             consumer.accept("hello consumer !");
36             System.out.println("---------------");
37 
38             //Lambda表达式
39     //      Consumer<String> con = (t) -> System.out.println(t);
40             Consumer<String> con = t -> System.out.println(t);
41             con.accept("hello Lambda !");
42         }
43 
44         @Test
45         public void test3(){
46             Comparator<Integer> comparator = (x,y) -> {
47                 System.out.println("相加结果是:"+(x+y));
48                 return Integer.compare(x,y);
49             };
50 
51             int compare = comparator.compare(1, 2);
52             System.out.println(compare);
53         }
54 
55         @Test
56         public void test4(){
57             Comparator<Integer> comparator = (x,y) -> Integer.compare(x,y);
58 
59             int compare = comparator.compare(1, 2);
60             System.out.println(compare);
61         }
62 
63         @Test
64         public void test5(){
65             show(new HashMap<>());
66         }
67 
68         public void show(Map<String,Integer> map){
69 
70         }
71     }

 

函数式接口

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

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

 1  /**
 2      * 函数式接口
 3      */
 4     public class TestFunction {
 5 
 6         //Consumer<T>消费型接口
 7         @Test
 8         public void test1(){
 9             cost(8888, (m) -> System.out.println("共消费:" + m + "元"));
10         }
11 
12         public void cost(double money,Consumer<Double> con){
13             con.accept(money);
14         }
15 
16         //Supplier<T> 供给型接口
17         @Test
18         public void test2(){
19             List<Integer> list = getNumList(8, () -> (int)(Math.random() * 100));
20             for (Integer integer : list) {
21                 System.out.println(integer);
22             }
23         }
24 
25         //产生指定数量的整数,放入集合中
26         public List<Integer> getNumList(int num,Supplier<Integer> sup){
27             List<Integer> list = new ArrayList<Integer>();
28 
29             for (int i = 0; i < num; i++) {
30                 Integer n = sup.get();
31                 list.add(n);
32             }
33 
34             return list;
35         }
36 
37         //Function<T,R> 函数型接口
38         @Test
39         public void test3(){
40             String string = strHandler(" 函数型接口测试 ", (str) -> str.trim().substring(0, 5));
41             System.out.println(string);
42         }
43 
44         //用于处理字符串
45         public String strHandler(String str,Function<String, String> fun){
46             return fun.apply(str);
47         }
48 
49         //Predicate<T> 断言型接口
50         @Test
51         public void test4(){
52             List<String> list = Arrays.asList("hello","Lambda","ok");
53             List<String> strList = filterStr(list, (s) -> s.length() > 3);
54             for (String string : strList) {
55                 System.out.println(string);
56             }
57         }
58 
59         //将满足条件的字符串,放入集合中
60         public List<String> filterStr(List<String> list, Predicate<String> pre){
61             List<String> strList = new ArrayList<>();
62 
63             for (String str : list) {
64                 if (pre.test(str)) {
65                     strList.add(str);
66                 }
67             }
68             return strList;
69         }
70     }

 

其他接口

方法引用与构造器引用

方法引用

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

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

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

构造器引用

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

数组引用

格式: type[] :: new

 1  /**
 2      * 方法引用:若Lambda 体中的内容有方法已经实现了,我们可以使用"方法引用"
 3      */
 4     public class TestMethodRef {
 5 
 6         @Test
 7         public void test1(){
 8             Consumer<String> con = (x) -> System.out.println(x);
 9             con.accept("shuai");
10 
11             //方法引用,对象::实例方法名
12             Consumer<String> consumer = System.out::println;
13             consumer.accept("test");
14         }
15 
16         @Test
17         public void test2(){
18             Person person = new Person();
19             Supplier<String> supplier = () -> person.getName();
20             String str = supplier.get();
21             System.err.println(str);
22 
23             //方法引用,对象::实例方法名
24             Supplier<Integer> sup = person::getAge;
25             Integer age = sup.get();
26             System.out.println(age);
27         }
28 
29         //类::静态方法名
30         @Test
31         public void test3(){
32             Comparator<Integer> com = (x,y) -> Integer.compare(x, y);
33             //使用前提,compare的参数和返回值与Comparator一致
34             Comparator<Integer> comparator = Integer :: compare;
35         }
36 
37         //类::实例方法名
38         @Test
39         public void test4(){
40             BiPredicate<String, String> bp = (x,y) -> x.equals(y);
41             //使用条件:第一个参数是实例方法调用者,第二个参数是实例方法的参数
42             BiPredicate<String, String> biPredicate = String :: equals;
43         }
44 
45         //构造器引用
46         @Test
47         public void test5(){
48             Supplier<Person> sup = () -> new Person();
49 
50             //构造器引用方式
51             Supplier<Person> supplier = Person :: new;
52             Person person = supplier.get();
53             System.out.println(person);
54         }
55 
56         //构造器引用
57         @Test
58         public void test6(){
59             Function<Integer, Person> fun = (x) -> new Person(x);
60 
61             Function<Integer, Person> function = Person :: new;
62             Person person = function.apply(2);
63             System.out.println(person);
64             System.out.println("--------------------");
65 
66             BiFunction<String, Integer, Person> biFunction = Person :: new;
67             Person person2 = biFunction.apply("张三", 23);
68             System.out.println(person2);
69         }
70 
71         //数组引用
72         @Test
73         public void test7(){
74             Function<Integer, String[]> fun = (x) -> new String[x]; 
75             String[] strs = fun.apply(8);
76             System.out.println(strs.length);
77 
78             Function<Integer, String[]> function = String[] :: new;
79             String[] strArray = function.apply(6);
80             System.out.println(strArray.length);
81         }
82     }

 

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) :

 1  //创建Stream
 2     @Test
 3     public void test1(){
 4         //1.可以通过Collection系列集合提供的stream() 或parallelStream()
 5         List<String> list = new ArrayList<>();
 6         Stream<String> stream = list.stream();
 7 
 8         //2.通过Arrays中静态方法 stream() 获取数组流
 9         Person[] persons = new Person[10];
10         Stream<Person> stream2 = Arrays.stream(persons);
11 
12         //3.通过Stream类中的静态方法 of()
13         Stream<String> stream3 = Stream.of("a","b","c");
14 
15         //4.创建无限流
16         //迭代
17         Stream<Integer> stream4 = Stream.iterate(0, (x) -> x + 2);
18         stream4.limit(8).forEach(System.out :: println);
19 
20         //生成
21         Stream.generate(() -> Math.random()).limit(6)
22             .forEach(System.out :: println);
23     }       

 

Stream 的中间操作

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

筛选与切片

映射

排序

  1   /**
  2      * Stream API的中间操作
  3      */
  4     public class TestSteamAPI2 {
  5 
  6         List<Person> persons = Arrays.asList(
  7                 new Person(2, "钱四", 24),
  8                 new Person(1, "张三", 33),
  9                 new Person(2, "李四", 24),
 10                 new Person(3, "王五", 65),
 11                 new Person(4, "赵六", 26),
 12                 new Person(4, "赵六", 26),
 13                 new Person(5, "陈七", 27)
 14         );
 15 
 16         //内部迭代,由Stream API完成
 17         @Test
 18         public void test1(){
 19             //中间操作,不会执行任何操作
 20             Stream<Person> stream = persons.stream()
 21                                         .filter((e) -> {
 22                                             System.out.println("Stream的中间操作");
 23                                             return e.getAge() > 25;
 24                                         });
 25             //终止操作,一次性执行全部内容,即"惰性求值"
 26             stream.forEach(System.out :: println);
 27         }
 28 
 29         //外部迭代
 30         @Test
 31         public void test2(){
 32             Iterator<Person> iterator = persons.iterator();
 33             while (iterator.hasNext()) {
 34                 System.out.println(iterator.next());
 35             }
 36         }
 37 
 38         //limit,截断
 39         @Test
 40         public void test3(){
 41             persons.stream()
 42                 .filter((e) -> {
 43                     System.out.println("迭代操作"); //短路
 44                     return e.getAge() > 24;
 45                 })
 46                 .limit(2)
 47                 .forEach(System.out :: println);
 48         }
 49 
 50         //跳过skip,distinct去重(要重写equals和hashcode)
 51         @Test
 52         public void test4(){
 53             persons.stream()
 54                     .filter((e) -> e.getAge() > 23)
 55                     .skip(2)
 56                     .distinct()
 57                     .forEach(System.out :: println);
 58         }
 59 
 60         //映射
 61         @Test
 62         public void test5(){
 63             List<String> list = Arrays.asList("a","bb","c","d","e");
 64 
 65             list.stream().map((str) -> str.toUpperCase())
 66                 .forEach(System.out :: println);
 67             System.out.println("---------------");
 68 
 69             persons.stream().map((Person :: getName)).forEach(System.out :: println);
 70             System.out.println("---------------");
 71 
 72             Stream<Stream<Character>> stream = list.stream()
 73                 .map(TestSteamAPI2 :: filterCharacter);
 74 
 75             stream.forEach((s) -> {
 76                 s.forEach(System.out :: println);
 77             });
 78             System.out.println("-----------------");
 79 
 80             //flatMap
 81             Stream<Character> stream2 = list.stream()
 82                 .flatMap(TestSteamAPI2 :: filterCharacter);
 83             stream2.forEach(System.out :: println);
 84         }
 85 
 86         //处理字符串
 87         public static Stream<Character> filterCharacter(String str){
 88             List<Character> list = new ArrayList<>();
 89 
 90             for (Character character : str.toCharArray()) {
 91                 list.add(character);
 92             }
 93             return list.stream();
 94         }
 95 
 96         //排序
 97         @Test
 98         public void test6(){
 99             List<String> list = Arrays.asList("bb","c","aa","ee","ddd");
100 
101             list.stream()
102                 .sorted() //自然排序
103                 .forEach(System.out :: println);
104             System.out.println("------------");
105 
106             persons.stream()
107                     .sorted((p1,p2) -> {
108                         if (p1.getAge() == p2.getAge()) {
109                             return p1.getName().compareTo(p2.getName());
110                         } else {
111                             return p1.getAge() - p2.getAge();
112                         }
113                     }).forEach(System.out :: println);
114 
115         }
116 
117     }

 

Stream 的终止操作

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

查找与匹配

归约

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

收集

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

   
  1  /**
  2      * Stream API的终止操作
  3      */
  4     public class TestSteamAPI3 {
  5 
  6         List<Person> persons = Arrays.asList(
  7                 new Person(2, "钱四", 24,Status.YOUNG),
  8                 new Person(1, "张三", 23,Status.YOUNG),
  9                 new Person(2, "李四", 24,Status.YOUNG),
 10                 new Person(3, "王五", 65,Status.OLD),
 11                 new Person(4, "赵六", 26,Status.MIDDLE),
 12                 new Person(4, "赵六", 56,Status.OLD),
 13                 new Person(5, "陈七", 27,Status.MIDDLE)
 14         );
 15 
 16         //查找与匹配
 17         @Test
 18         public void test1(){
 19             boolean b = persons.stream()
 20                                 .allMatch((e) -> e.getStatus().equals(Status.YOUNG));
 21             System.out.println(b);
 22 
 23             boolean b2 = persons.stream()
 24                     .anyMatch((e) -> e.getStatus().equals(Status.YOUNG));
 25             System.out.println(b2);
 26 
 27             boolean b3 = persons.stream()
 28                     .noneMatch((e) -> e.getStatus().equals(Status.MIDDLE));
 29             System.out.println(b3);
 30 
 31             Optional<Person> op = persons.stream()
 32                     .sorted((e1,e2) -> Integer.compare(e1.getAge(), e2.getAge()))
 33                     .findFirst();
 34             System.out.println(op.get());
 35 
 36             Optional<Person> optional = persons.stream()
 37                     .filter((e) -> e.getStatus().equals(Status.OLD))
 38                     .findAny();
 39             System.out.println(optional.get());
 40         }
 41 
 42         //最大,最小
 43         @Test
 44         public void test2(){
 45             long count = persons.stream()
 46                     .count();
 47             System.out.println(count);
 48 
 49             Optional<Person> optional = persons.stream()
 50                     .max((e1,e2) -> Integer.compare(e1.getId(), e2.getId()));
 51             System.out.println(optional.get());
 52 
 53             Optional<Integer> op = persons.stream()
 54                     .map(Person :: getAge)
 55                     .min(Integer :: compare);
 56             System.out.println(op.get());
 57         }
 58 
 59         //归约
 60         @Test
 61         public void test3(){
 62             List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8);
 63 
 64             Integer sum = list.stream()
 65                 .reduce(0, (x,y) -> x + y);
 66             System.out.println(sum);
 67             System.out.println("------------");
 68 
 69             Optional<Integer> optional = persons.stream()
 70                     .map(Person :: getAge)
 71                     .reduce(Integer :: sum);
 72             System.out.println(optional.get());
 73         }
 74 
 75         //收集
 76         @Test
 77         public void test4(){
 78             List<String> list = persons.stream()
 79                     .map(Person :: getName)
 80                     .collect(Collectors.toList());
 81             list.forEach(System.out :: println);
 82             System.out.println("------------");
 83 
 84             Set<String> set = persons.stream()
 85                     .map(Person :: getName)
 86                     .collect(Collectors.toSet());
 87             set.forEach(System.out :: println);
 88             System.out.println("------------");
 89 
 90             HashSet<String> hashSet = persons.stream()
 91                     .map(Person :: getName)
 92                     .collect(Collectors.toCollection(HashSet :: new));
 93             hashSet.forEach(System.out :: println);
 94         }
 95 
 96         @Test
 97         public void test5(){
 98             Long count = persons.stream()
 99                     .collect(Collectors.counting());
100             System.out.println("总人数="+count);
101             System.out.println("----------------");
102 
103             //平均值
104             Double avg = persons.stream()
105                     .collect(Collectors.averagingInt(Person :: getAge));
106             System.out.println("平均年龄="+avg);
107             System.out.println("---------------");
108 
109             //总和
110             Integer sum = persons.stream()
111                     .collect(Collectors.summingInt(Person :: getAge));
112             System.out.println("年龄总和="+sum);
113             System.out.println("----------------");
114 
115             //最大值
116             Optional<Person> max = persons.stream()
117                     .collect(Collectors.maxBy((e1,e2) -> Integer.compare(e1.getAge(), e2.getAge())));
118             System.out.println("最大年龄是"+max.get());
119             System.out.println("----------------");
120 
121             //最小值
122             Optional<Person> min = persons.stream()
123                     .collect(Collectors.minBy((e1,e2) -> Integer.compare(e1.getAge(), e2.getAge())));
124             System.out.println("最小年龄是"+min.get());
125         }
126 
127         //分组
128         @Test
129         public void test6(){
130             Map<Status, List<Person>> map = persons.stream()
131                     .collect(Collectors.groupingBy(Person :: getStatus));//根据年龄层分组
132             System.out.println(map);
133         }
134 
135         //多级分组
136         @Test
137         public void test7(){
138             Map<Status, Map<String, List<Person>>> map = persons.stream()
139                     .collect(Collectors.groupingBy(Person :: getStatus ,Collectors.groupingBy((e) -> {
140                         if (e.getId()%2 == 1) {
141                             return "单号";
142                         } else {
143                             return "双号";
144                         } 
145                     })));
146             System.out.println(map);
147         }
148 
149         //分区
150         @Test
151         public void test8(){
152             Map<Boolean, List<Person>> map = persons.stream()
153                     .collect(Collectors.partitioningBy((e) -> e.getAge() > 30));
154             System.out.println(map);
155         }
156 
157         //IntSummaryStatistics
158         @Test
159         public void test9(){
160             IntSummaryStatistics iss = persons.stream()
161                     .collect(Collectors.summarizingInt(Person :: getAge));
162             System.out.println(iss.getSum());
163             System.out.println(iss.getAverage());
164             System.out.println(iss.getMax());
165         }
166 
167         @Test
168         public void test10(){
169             String str = persons.stream()
170                     .map(Person :: getName)
171                     .collect(Collectors.joining(",","人员名单:","等"));
172             System.out.println(str);
173         }
174     }

 

并行流与串行流

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

 1  /**
 2      * FrokJoin框架
 3      */
 4     public class ForkJoinCalculate extends RecursiveTask<Long>{
 5         private static final long serialVersionUID = 1L;
 6 
 7         private long start;
 8         private long end;
 9 
10         private static final long THRESHOLD = 10000;
11 
12         public ForkJoinCalculate() {
13 
14         }
15 
16         public ForkJoinCalculate(long start, long end) {
17             this.start = start;
18             this.end = end;
19         }
20 
21 
22         @Override
23         protected Long compute() {
24             long length = end - start ;
25             if (length <= THRESHOLD) {
26                 long sum = 0;
27                 for (long i = start; i <= end; i++) {
28                     sum += i;
29                 }
30                 return sum;
31             }else {
32                 long middle = (start + end) / 2; 
33                 ForkJoinCalculate left = new ForkJoinCalculate();
34                 left.fork();//拆分子任务,同时压入线程队列
35 
36                 ForkJoinCalculate right = new ForkJoinCalculate();
37                 right.fork();
38                 return left.join() + right.join();
39             }
40         }
41 
42     }

 

测试并行流

 1  public class TestForkJoin {
 2 
 3         /**
 4          * FrokJoin框架
 5          */
 6         @Test
 7         public void test1(){
 8             Instant start = Instant.now();
 9 
10             ForkJoinPool pool = new ForkJoinPool();
11             ForkJoinTask<Long> task = new ForkJoinCalculate(0,10000000000L);
12             Long sum = pool.invoke(task);
13             System.out.println(sum);
14 
15             Instant end = Instant.now();
16             System.out.println(Duration.between(start,end).toMillis());
17         }
18 
19         /**
20          * for循环
21          */
22         @Test
23         public void test2(){
24             Instant start = Instant.now();
25             long sum = 0L;
26 
27             for (long i = 0; i <= 10000000000L; i++) {
28                 sum += i;
29             }
30             System.out.println(sum);
31 
32             Instant end = Instant.now();
33             System.out.println(Duration.between(start, end).toMillis());
34         }
35 
36         /**
37          * Java8并行流
38          */
39         @Test
40         public void test3(){
41             Instant start = Instant.now();
42             LongStream.rangeClosed(0, 10000000000L)
43                         .parallel()
44                         .reduce(0,Long :: sum);
45             Instant end = Instant.now();
46             System.out.println(Duration.between(start, end).toMillis());
47         }
48     }

 

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

接口中的默认方法

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

接口中的静态方法

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

 1   public interface MyInterface {
 2 
 3         default String getName(){
 4             return "接口测试";
 5         }
 6 
 7         public static void show(){
 8             System.out.println("接口中的静态方法");
 9         }
10     }

 

新时间日期 API

LocalDate、LocalTime、LocalDateTime

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

传统写法:

 1  public class DateFormatThreadLocal {
 2 
 3         private static final ThreadLocal<DateFormat> tl = new ThreadLocal<DateFormat>(){
 4             protected DateFormat initialValue() {
 5                 return new SimpleDateFormat("yyyyMMdd");
 6             }
 7         };
 8 
 9         public static Date convert(String source) throws ParseException{
10             return tl.get().parse(source);
11         }
12     }       
13 
14     public static void main(String[] args) throws InterruptedException, ExecutionException {
15 //      SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
16 
17         Callable<Date> callable = new Callable<Date>() {
18 
19             @Override
20             public Date call() throws Exception {
21 //              return sdf.parse("20170521");
22                 return DateFormatThreadLocal.convert("20170521");
23             }
24 
25         };
26         ExecutorService pool = Executors.newFixedThreadPool(10);
27         List<Future<Date>> results = new ArrayList<>();
28         for (int i = 0; i < 8; i++) {
29             results.add(pool.submit(callable));
30         }
31         for (Future<Date> future : results) {
32             System.out.println(future.get());
33         }
34 
35         //关闭资源
36         pool.shutdown();
37     }

 

新特性:

 1  public static void main(String[] args) throws InterruptedException, ExecutionException {
 2         DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
 3         Callable<LocalDate> callable = new Callable<LocalDate>() {
 4 
 5             @Override
 6             public LocalDate call() throws Exception {
 7                 return LocalDate.parse("20170521",dtf);
 8             }
 9 
10         };
11         ExecutorService pool = Executors.newFixedThreadPool(10);
12         List<Future<LocalDate>> results = new ArrayList<>();
13         for (int i = 0; i < 8; i++) {
14             results.add(pool.submit(callable));
15         }
16         for (Future<LocalDate> future : results) {
17             System.out.println(future.get());
18         }
19 
20         //关闭资源
21         pool.shutdown();
22 }

 

LocalDate LocalTime LocalDateTime

 1  //1.LocalDate LocalTime LocalDateTime
 2     @Test
 3     public void test1(){
 4         LocalDateTime ldt = LocalDateTime.now();
 5         System.out.println(ldt);
 6 
 7         LocalDateTime ldt2 = LocalDateTime.of(2017, 05, 21, 21, 43, 55, 33);
 8         System.out.println(ldt2);
 9 
10         LocalDateTime ldt3 = ldt.plusYears(3);
11         System.out.println(ldt3);
12 
13         LocalDateTime ldt4 = ldt.minusMonths(5);
14         System.out.println(ldt4);
15     }

 

Instant 时间戳

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

 1   //2.Instant
 2     @Test
 3     public void test2(){
 4         Instant now = Instant.now();
 5         System.out.println(now);
 6 
 7         OffsetDateTime atOffset = now.atOffset(ZoneOffset.ofHours(6));
 8         System.out.println(atOffset);
 9 
10         Instant ins = Instant.ofEpochSecond(60);
11         System.out.println(ins);
12     }

 

Duration 和 Period

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

     1 //3.Duration 
     2 @Test
     3 public void test3(){
     4     Instant now = Instant.now();
     5     try {
     6         Thread.sleep(1000);
     7     } catch (InterruptedException e) {
     8         e.printStackTrace();
     9     }
    10     Instant now2 = Instant.now();
    11     //计算时间差
    12     Duration duration = Duration.between(now, now2);
    13     System.out.println(duration.getSeconds());
    14     System.out.println("----------------");
    15 
    16     LocalTime lt1 = LocalTime.now();
    17     try {
    18         Thread.sleep(1000);
    19     } catch (InterruptedException e) {
    20         e.printStackTrace();
    21     }
    22     LocalTime lt2 = LocalTime.now();
    23     System.out.println(Duration.between(lt1, lt2).toMillis());
    24 }
    25 
    26 //4.Period
    27 @Test
    28 public void test4(){
    29     LocalDate ld1 = LocalDate.of(2017, 1, 1);
    30     LocalDate ld2 = LocalDate.now();
    31     Period period = Period.between(ld1, ld2);
    32     System.out.println(period.getYears());
    33     System.out.println(period.getMonths());
    34     System.out.println(period.getDays());
    35 }

     

日期的操作

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

     1 //5.TemporalAdjuster:时间校正器
     2 @Test
     3 public void test5(){
     4     LocalDateTime ldt = LocalDateTime.now();
     5     System.out.println(ldt);
     6 
     7     LocalDateTime ldt2 = ldt.withDayOfMonth(8);
     8     System.out.println(ldt2);
     9 
    10     LocalDateTime ldt3 = ldt.with(TemporalAdjusters.next(DayOfWeek.SATURDAY));
    11     System.out.println(ldt3);
    12 
    13     //自定义
    14     LocalDateTime ldt5 =  ldt.with((l) -> {
    15         LocalDateTime ldt4 = (LocalDateTime) l;
    16         DayOfWeek dow = ldt4.getDayOfWeek();
    17         if (dow.equals(DayOfWeek.FRIDAY)) {
    18             return ldt4.plusDays(3);
    19         }else if (dow.equals(DayOfWeek.SATURDAY)) {
    20             return ldt4.plusDays(2);
    21         } else {
    22             return ldt4.plusDays(1);
    23         }
    24     });
    25     //下个工作日
    26     System.out.println(ldt5);
    27 }

     

  • 1

解析与格式化

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

 1  //DateTimeFormatter:格式化时间/日期
 2     @Test
 3     public void test6(){
 4         DateTimeFormatter dtf = DateTimeFormatter.ISO_DATE_TIME;
 5         LocalDateTime ldt = LocalDateTime.now();
 6 
 7         System.out.println(ldt);
 8         String format = ldt.format(dtf);
 9         System.out.println(format);
10         System.out.println("------------");
11         DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
12         String format2 = dtf2.format(ldt);
13         System.out.println(format2);
14 
15         LocalDateTime ldt2 = ldt.parse(format2,dtf2);
16         System.out.println(ldt2);
17     }

 

 

时区的处理

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

 1  //ZonedDate ZoneTime ZoneDateTime
 2     @Test
 3     public void test7(){
 4         LocalDateTime ldt = LocalDateTime.now(ZoneId.of("Europe/Tallinn"));
 5         System.out.println(ldt);
 6 
 7         LocalDateTime ldt2 = LocalDateTime.now(ZoneId.of("Europe/Tallinn"));
 8         ZonedDateTime zdt = ldt2.atZone(ZoneId.of("Asia/Shanghai"));
 9         System.out.println(zdt);
10     }

 

与传统日期处理的转换

其他新特性

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

 1 /**
 2      * Optional类
 3      */
 4     public class TestOptional {
 5 
 6         @Test
 7         public void test1(){
 8             //参数不能为空
 9             Optional<Person> op = Optional.of(new Person());
10 
11             Person person = op.get();
12             System.out.println(person);
13         }
14 
15         @Test
16         public void test2(){
17             //构建空optional
18             Optional<Person> op = Optional.empty();
19             System.out.println(op.get());
20         }
21 
22         @Test
23         public void test3(){
24             //如果为null,调用empty,如果不为null,调用of
25             Optional<Person> op = Optional.ofNullable(null);
26     //      Optional<Person> op = Optional.ofNullable(new Person());
27             if (op.isPresent()) {
28                 System.out.println(op.get());
29             }
30 
31             //有值就用值,没值就替代
32             Person person = op.orElse(new Person("张三", 23));
33             System.out.println(person);
34         }
35     }

 

重复注解与类型注解

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

 1  @Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
 2     @Retention(RetentionPolicy.RUNTIME)
 3     public @interface MyAnnotations {
 4 
 5         MyAnnotation[] value();
 6     }
 7 
 8     @Repeatable(MyAnnotations.class)
 9     @Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, ElementType.TYPE_PARAMETER})
10     @Retention(RetentionPolicy.RUNTIME)
11     public @interface MyAnnotation {
12 
13         String value() default "aric";
14     }
15 
16     /**
17      * 重复注解与类型注解
18      */
19     public class TestAnnotation {
20 
21         @MyAnnotation("hello")
22         @MyAnnotation("test")
23         public void show(@MyAnnotation("a") String str){
24             System.out.println(str);
25         }
26     }