新特性简介

  1. 速度更快
  2. 代码更少(增加了新的语法Lambda表达式)
  3. 强大的 Stream API
  4. 便于并行
  5. 最大化减少空指针异常 Optional

Lambda表达式

为什么使用Lambda表达式

概述

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//原来的匿名内部类
@Test
public void test1(){
Comparator<String> com = new Comparator<String>(){
@Override
public int compare(String o1, String o2) {
return Integer.compare(o1.length(), o2.length());
}
};

TreeSet<String> ts = new TreeSet<>(com);

TreeSet<String> ts2 = new TreeSet<>(new Comparator<String>(){
@Override
public int compare(String o1, String o2) {
return Integer.compare(o1.length(), o2.length());
}

});
}

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

案例分析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import java.util.Objects;

public class Employee {
private int id;
private String name;
private int age;
private double salary;

public Employee() {
}

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

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

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

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public double getSalary() {
return salary;
}

public void setSalary(double salary) {
this.salary = salary;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Employee)) return false;
Employee employee = (Employee) o;
return getId() == employee.getId() && getAge() == employee.getAge() && Double.compare(employee.getSalary(), getSalary()) == 0 && Objects.equals(getName(), employee.getName());
}

@Override
public int hashCode() {
return Objects.hash(getId(), getName(), getAge(), getSalary());
}

@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", salary=" + salary +
'}';
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
List<Employee> emps = Arrays.asList(
new Employee(101, "小新", 18, 9999.99),
new Employee(102, "伟伟", 59, 6666.66),
new Employee(103, "鑫鑫", 28, 3333.33),
new Employee(104, "创儿", 20, 7777.77),
new Employee(105, "小寒", 38, 5555.55)
);

//需求:获取公司中年龄小于 35 的员工信息
public List<Employee> filterEmployeeAge(List<Employee> emps){
List<Employee> list = new ArrayList<>();
for (Employee emp : emps) {
if(emp.getAge() <= 35){
list.add(emp);
}
}
return list;
}

//需求:获取公司中工资大于 5000 的员工信息
public List<Employee> filterEmployeeSalary(List<Employee> emps){
List<Employee> list = new ArrayList<>();
for (Employee emp : emps) {
if(emp.getSalary() >= 5000){
list.add(emp);
}
}
return list;
}

优化1: 策略设计模式

1
2
3
4
5
6
7
8
9
10
//优化方式一:策略设计模式
public List<Employee> filterEmployee(List<Employee> emps, MyPredicate<Employee> mp){
List<Employee> list = new ArrayList<>();
for (Employee employee : emps) {
if(mp.test(employee)){
list.add(employee);
}
}
return list;
}
1
2
3
public interface MyPredicate<T> {
public boolean test(T t);
}
1
2
3
4
5
6
public class FilterEmployeeForAge implements MyPredicate<Employee>{
@Override
public boolean test(Employee t) {
return t.getAge() <= 35;
}
}
1
2
3
4
5
6
public class FilterEmployeeForSalary implements MyPredicate<Employee> {
@Override
public boolean test(Employee t) {
return t.getSalary() >= 5000;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
@Test
public void test(){
List<Employee> list = filterEmployee(emps, new FilterEmployeeForAge());
for (Employee employee : list) {
System.out.println(employee);
}
System.out.println("------------------------------------------");
List<Employee> list2 = filterEmployee(emps, new FilterEmployeeForSalary());
for (Employee employee : list2) {
System.out.println(employee);
}
}

优化2: 匿名内部类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//优化方式二:匿名内部类
@Test
public void test3(){
List<Employee> list = filterEmployee(emps, new MyPredicate<Employee>() {
@Override
public boolean test(Employee t) {
return t.getId() <= 103;
}
});

for (Employee employee : list) {
System.out.println(employee);
}
}

优化3: Lambda 表达式

1
2
3
4
5
6
7
8
9
10
11
//优化方式三:Lambda 表达式
@Test
public void test4(){
List<Employee> list = filterEmployee(emps, (e) -> e.getAge() <= 35);
list.forEach(System.out::println);

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

List<Employee> list2 = filterEmployee(emps, (e) -> e.getSalary() >= 5000);
list2.forEach(System.out::println);
}

优化4: Stream API

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//优化方式四:Stream API
@Test
public void test5(){
emps.stream()
.filter((e) -> e.getAge() <= 35)
.forEach(System.out::println);

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

emps.stream()
.map(Employee::getName)
.limit(3)
.sorted()
.forEach(System.out::println);
}

Lambda表达式语法

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

  • 左侧:指定了 Lambda 表达式需要的所有参数
  • 右侧:指定了 Lambda 体,即 Lambda 表达式要执行的功能
  1. 语法格式一:无参,无返回值,Lambda 体只需一条语句
1
2
Runnable r = () -> System.out.println("HelloWorld~");
r.run();
  1. 语法格式二:Lambda 需要一个参数,无返回值
1
2
Consumer<String> con = (a) -> System.out.println(a);
con.accept("我是Lambda~");
  1. 语法格式三:Lambda 只需要一个参数时,参数的小括号可以省略
1
2
Consumer<String> con = a -> System.out.println(a);
con.accept("我是Lambda~");
  1. 语法格式四:Lambda 需要两个参数,且Lambda体中有多条语句,并且有返回值
1
2
3
4
5
6
Comparator<Integer> comparator = (a,b) -> {
System.out.println("函数式接口");
return Integer.compare(a,b);
};
int compare = comparator.compare(2, 4);
System.out.println(compare);
  1. 语法格式五:当 Lambda 体只有一条语句时,return 与大括号可以省略
1
2
3
Comparator<Integer> comparator = (a,b) -> Integer.compare(a,b);
int compare = comparator.compare(2, 4);
System.out.println(compare);
  1. 语法格式六:数据类型可以省略,因为可由编译器推断得出, 称为“类型推断”

类型推断

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

函数式接口

什么是函数式接口

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

自定义函数式接口

1
2
3
4
@FunctionalInterface
public interface MyFunc<T> {
public T getValue(T t);
}

作为参数传递Lambda表达式

1
2
3
4
5
6
7
8
9
public Integer operation(Integer num, MyFunc<Integer> myFunc){
return myFunc.getValue(num);
}

@Test
public void test(){
Integer result = operation(10,(x) -> x * x);
System.out.println(result);
}

注意:作为参数传递 Lambda 表达式:为了将 Lambda 表达式作为参数传递,接收 Lambda 表达式的参数类型必须是与该 Lambda 表达式兼容的函数式接口的类型。

内置四大核心函数式接口

其他接口

Lambda练习

练习1:调用Collections.sort()方法,通过定制排序比较两个Employee(优先按照年龄比较,年龄相同按照姓名排序),使用Lambda作为参数传递。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
List<Employee> emps = Arrays.asList(
new Employee(101, "小新", 18, 9999.99),
new Employee(102, "伟伟", 59, 6666.66),
new Employee(103, "鑫鑫", 28, 3333.33),
new Employee(104, "创儿", 20, 7777.77),
new Employee(105, "小寒", 38, 5555.55)
);

@Test
public void test1(){
Collections.sort(emps,(e1,e2) -> {
if (e1.getAge() == e2.getAge()){
return e1.getName().compareTo(e2.getName());
}
else {
return Integer.compare(e1.getAge(),e2.getAge());
}
});
for (Employee e : emps){
System.out.println(e);
}
}

练习2:

  1. 声明函数式接口,接口中声明抽象方法,public String getValue(String str);
  2. 声明类TestLambda,类中编写方法使用接口作为参数,将一个字符串转换为大写,并作为方法的返回值。
  3. 再将一个字符串的第二个和第四个索引位置进行截取子串。
1
2
3
4
@FunctionalInterface
public interface MyFunction {
String getValue(String str);
}
1
2
3
4
5
6
7
8
9
10
11
public String strHandler(String str, MyFunction mf){
return mf.getValue(str);
}

@Test
public void test(){
String upper = strHandler("abcAbc",(a -> a.toUpperCase(Locale.ROOT)));
System.out.println(upper);
String subString = strHandler("我在学习Lambda表达式", (b) -> b.substring(2,4));
System.out.println(subString);
}

练习3:

  1. 声明一个带两个泛型的函数式接口,泛型类型为<T,R>,T为参数,R为返回值
  2. 接口中声明对应抽象方法
  3. 在TestLambda类中声明方法,使用接口作为参数,计算两个long型参数的和
  4. 再计算两个long型参数的乘积
1
2
3
4
@FunctionalInterface
public interface MyFunction<T,R> {
R getValue(T t1, T t2);
}
1
2
3
4
5
6
7
8
9
public void op(Long l1, Long l2, MyFunction<Long,Long> mf){
System.out.println(mf.getValue(l1,l2));
}

@Test
public void test(){
op(100L, 200L, (x,y) -> x + y);
op(100L, 200L, (x,y) -> x * y);
}

方法引用与构造器引用

方法引用

当要传递给 Lambda 体的操作,已经有实现的方法了,可以使用方法引用!

实现抽象方法的参数列表,必须与方法引用方法的参数列表保持一致!

方法引用:使用操作符 “::” 将方法名和对象或类的名字分隔开来。 如下三种主要使用情况:

  • 对象::实例方法
  • 类::静态方法
  • 类::实例方法

注意:当需要引用方法的第一个参数是调用对象,并且第二个参数是需要引用方法的第二个参数(或无参数)时:ClassName::methodName

构造器引用

格式:ClassName::new

与函数式接口相结合,自动与函数式接口中方法兼容。

可以把构造器引用赋值给定义的方法,与构造器参数列表要与接口中抽象方法的参数列表一致!

数组引用

格式:type[]::new

强大的Stream API

关于Stream

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

  • 流(Stream) 到底是什么呢?

    • 是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列。“集合讲的是数据,流讲的是计算!”
  • 注意:

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

Stream操作三个步骤

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

创建Stream

由Collection接口创建

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

  • default Stream<E> stream() : 返回一个顺序流
  • default Stream<E> parallelStream() : 返回一个并行流
1
2
3
//通过Collection系列集合提供的Stream()和parallelStream()
List<String> list = new ArrayList<>();
Stream<String> stream = list.stream();

由数组创建流

Java8 中的 Arrays 的静态方法 stream()可以获取数组流:

  • static <T> Stream<T> stream(T[] array): 返回一个流
1
2
3
//通过Arrays中的静态方法stream()获取数组流
Employee[] employees = new Employee[10];
Stream<Employee> stream1 = Arrays.stream(employees);

重载形式,能够处理对应基本类型的数组:

  • public static IntStream stream(int[] array)
  • public static LongStream stream(long[] array)
  • public static DoubleStream stream(double[] array)

由值创建流

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

  • public static<T> Stream<T> of(T... values) : 返回一个流
1
2
//通过Stream类重的静态方法of()
Stream<String> stream2 = Stream.of("aa", "bb", "dd", "cc");

由函数创建流-创建无限流

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

  • 迭代

    • public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f)
    1
    2
    //迭代
    Stream<Integer> stream3 = Stream.iterate(0, (x) -> x + 2);
  • 生成

    • public static<T> Stream<T> generate(Supplier<T> s)
    1
    2
    3
    4
    //生成
    Stream.generate(() -> Math.random())
    .limit(5)
    .forEach(System.out::println);

Stream中间操作

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

筛选与切片

  • filter(Predicate p):接收 Lambda,从流中排除某些元素。
  • distinct():筛选,通过流所生成元素hashCode()equals()去除重复元素
  • limit(long maxSize):截断流,使其元素不超过给定数量。
  • skip(long n):跳过元素,返回一个扔掉了前n个元素的流。若流中元素不足n个,则返回一个空流。与limit(n)互补

映射

  • map(Function f):接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
  • mapToDouble(ToDoubleFunction f):接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 DoubleStream。
  • mapToInt(ToIntFunction f):接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的IntStream。
  • mapToLong(ToLongFunction f):接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的LongStream。
  • flatMap(Function f):接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。

排序

  • sorted():产生一个新流,其中按自然顺序排序
  • sorted(Comparator comp):产生一个新流,其中按比较器顺序排序

Stream终止操作

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

查找与匹配

  • allMatch(Predicate p):检查是否匹配所有元素
  • anyMatch(Predicate p):检查是否至少匹配一个元素
  • noneMatch(Predicate p):检查是否没有匹配所有元素
  • findFirst():返回第一个元素
  • findAny():返回当前流中的任意元素
  • count():返回流中元素总数
  • max(Comparator c):返回流中最大值
  • min(Comparator c):返回流中最小值
  • forEach(Consumer c)内部迭代(使用 Collection 接口需要用户去做迭代,称为外部迭代。相反,Stream API 使用内部迭代——它帮你把迭代做了)

归约

  • reduce(T iden, BinaryOperator b):可以将流中元素反复结合起来,得到一个值。返回 T
  • reduce(BinaryOperator b):可以将流中元素反复结合起来,得到一个值。 返回 Optional<T>

备注:map 和 reduce 的连接通常称为map-reduce模式,因 Google 用它来进行网络搜索而出名。

收集

  • collect(Collector c):将流转换为其他形式。接收一个Collector接口的实现,用于给Stream中元素做汇总的方法

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

StreamAPI练习

练习1:给定一个数字列表,返回一个由每个数的平凡构成的列表。例如:给定【1,2,3,4,5】,返回【1,4,9,16,25】

1
2
3
4
5
6
7
@Test
public void test1(){
Integer[] numbers = new Integer[]{1,2,3,4,5};
Arrays.stream(numbers)
.mapToInt(x -> x * x)
.forEach(System.out::println);
}

练习2:用map和reduce方法数一数流中有多少个Employee

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
List<Employee> emps = Arrays.asList(
new Employee(101, "小新", 18, 9999.99),
new Employee(102, "伟伟", 59, 6666.66),
new Employee(103, "鑫鑫", 28, 3333.33),
new Employee(104, "创儿", 20, 7777.77),
new Employee(105, "小寒", 38, 5555.55)
);

@Test
public void test2(){
Optional<Integer> sum = emps.stream()
.map(employee -> 1)
.reduce(Integer::sum);
System.out.println(sum.get());
}

练习3:

  • 交易员类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package exer.StreamAPI2;

//交易员类
public class Trader {
private String name;
private String city;

public Trader() {
}

public Trader(String name, String city) {
this.name = name;
this.city = city;
}

public String getName() {
return name;
}

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

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

@Override
public String toString() {
return "Trader{" +
"name='" + name + '\'' +
", city='" + city + '\'' +
'}';
}
}
  • 交易类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package exer.StreamAPI2;

//交易类
public class Transaction {

private Trader trader;
private int year;
private int value;

public Transaction() {
}

public Transaction(Trader trader, int year, int value) {
this.trader = trader;
this.year = year;
this.value = value;
}

public Trader getTrader() {
return trader;
}

public void setTrader(Trader trader) {
this.trader = trader;
}

public int getYear() {
return year;
}

public void setYear(int year) {
this.year = year;
}

public int getValue() {
return value;
}

public void setValue(int value) {
this.value = value;
}

@Override
public String toString() {
return "Transaction{" +
"trader=" + trader +
", year=" + year +
", value=" + value +
'}';
}
}
  • 习题
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package exer.StreamAPI2;

import org.junit.Before;
import org.junit.Test;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class TestTransaction {

List<Transaction> transactions = null;

@Before
public void before(){
Trader raoul = new Trader("Raoul", "Cambridge");
Trader mario = new Trader("Mario", "Milan");
Trader alan = new Trader("Alan", "Cambridge");
Trader brian = new Trader("Brian", "Cambridge");

transactions = Arrays.asList(
new Transaction(brian, 2011, 300),
new Transaction(raoul, 2012, 1000),
new Transaction(raoul, 2011, 400),
new Transaction(mario, 2012, 710),
new Transaction(mario, 2012, 700),
new Transaction(alan, 2012, 950)
);
}

/**
* 1. 找出2011年发生的所有交易,并按交易额排序(从低到高)
*/
@Test
public void test1(){
transactions.stream()
.filter(t -> t.getYear() == 2011)
.sorted(Comparator.comparingInt(Transaction::getValue))
.forEach(System.out::println);
}

/**
* 2. 交易员都在哪些不同的城市工作过?
*/
@Test
public void test2(){
transactions.stream()
.map(t -> t.getTrader().getCity())
.distinct()
.forEach(System.out::println);
}

/**
* 3. 查找所有来自剑桥的交易员,并按姓名排序
*/
@Test
public void test3(){
transactions.stream()
.filter(t -> t.getTrader().getCity().equalsIgnoreCase("Cambridge"))
.map(Transaction::getTrader)
.sorted(Comparator.comparing(Trader::getName))
.distinct()
.forEach(System.out::println);
}

/**
* 4. 返回所有交易员的姓名字符串,按字母顺序排序
*/
@Test
public void test4(){
transactions.stream()
.map(Transaction::getTrader)
.map(Trader::getName)
.sorted()
.distinct()
.forEach(System.out::println);
}

/**
* 5. 有没有交易员是在米兰工作的?
*/
@Test
public void test5(){
System.out.println(transactions.stream()
.anyMatch(t -> t.getTrader().getCity().equals("Milan")));
}

/**
* 6. 打印生活在剑桥的交易员的所有交易额
*/
@Test
public void test6(){
System.out.println(transactions.stream()
.filter(e -> e.getTrader().getCity().equals("Cambridge"))
.map(Transaction::getValue)
.reduce(Integer::sum).get());
}

/**
* 7. 所有交易中,最高的交易额是多少
*/
@Test
public void test7(){
System.out.println(transactions.stream()
.map(Transaction::getValue)
.max(Integer::compare).get());
}

/**
* 8. 找到交易额最小的交易
*/
@Test
public void test8(){
System.out.println(transactions.stream()
.min(Comparator.comparingInt(Transaction::getValue))
.get());
}
}

并行流与串行流

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

Java 8 中将并行进行了优化,我们可以很容易的对数据进行并行操作。Stream API 可以声明性地通过parallel()sequential()在并行流与顺序流之间进行切换。

Fork/Join 框架

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

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

采用“工作窃取”模式(work-stealing): 当执行新的任务时它可以将其拆分分成更小的任务执行,并将小任务加到线程队列中,然后再从一个随机线程的队列中偷一个并把它放在自己的队列中。

相对于一般的线程池实现,fork/join框架的优势体现在对其中包含的任务的处理方式上。在一般的线程池中,如果一个线程正在执行的任务由于某些原因无法继续运行,那么该线程会处于等待状态。而在fork/join框架实现中,如果某个子问题由于等待另外一个子问题的完成而无法继续运行。那么处理该子问题的线程会主动寻找其他尚未运行的子问题来执行。这种方式减少了线程的等待时间,提高了性能。

Optional类

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

常用方法:

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

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

默认方法

概述

Java 8中允许接口中包含具有具体实现的方法,该方法称为 “默认方法”,默认方法使用 default 关键字修饰。

类优先原则

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

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

静态方法

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

新时间日期API

LocalDate、LocalTime、LocalDateTime

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

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

Instant 时间戳

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

Instant.now():默认获取UTC时区

Duration 和 Period

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

时间校正器

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

解析与格式化

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

  • 预定义的标准格式
  • 语言环境相关的格式
  • 自定义的格式

时区的处理

Java8 中加入了对时区的支持,带时区的时间为分别为:

  • ZonedDate
  • ZonedTime
  • ZonedDateTime

其中每个时区都对应着 ID,地区ID都为 “{区域}/{城市}” 的格式 例如:Asia/Shanghai 等

  • ZoneId:该类中包含了所有的时区信息
    • getAvailableZoneIds():可以获取所有时区时区信息
    • of(id):用指定的时区信息获取 ZoneId 对象

重复注解与类型注解

Java 8 对注解处理提供了两点改进:

  • 可重复的注解
  • 可用于类型的注解