java8新特性

​ 关于java8的新特性

  • 速度更快
    • 修改底层数据结构:HashMap(数组-链表-红黑数),HashSet,ConcurrentHashMap(CAS算法)
    • 修改垃圾回收机制(内存结构):取消堆中的永久区(PremGen)->回收条件苛刻,使用元空间(MetaSpace)->直接使用物理内存->加载类文件

底层数据结构:最核心HashMap:

​ HashMap如果不用哈希算法,用equals,效率极低。对比HashCode,没有直接进来。相同,通过equals内容比较不同,形成链表,后加的放前边,称为碰撞,但碰撞应该避免,因为链表元素过多,效率低。

​ equals和HashCode重写方法严谨一点,但还是避免不了,因为数组的索引值就几个。方法,提供加载因子,默认0,75,当元素到达哈希表的75%,进行扩容。把链表里面的元素进行重排序,新位置,碰撞概率变低。

​ 但极端情况,查找元素,查找到链表,查找到最后一个,查找效率变低。
1

​ 所以jdk1.8后,数组+链表+红黑数(二叉树一种)

​ 链表元素长度(个数)大于8,容量大于64,转换为红黑树。

​ 链表转为红黑树后,除了添加以外,其他的效率都高了。添加,链表直接在后面添加,在红黑树要比较大小后才添加。

​ 扩容以后,换位置不用重新计算,在原来哈希表的总长度+当前的位置,原来5,+3,在第8个位置。

​ HashSet变了,ConcurrenHashMap变了,改为CAS算法(无锁算法)

底层数据结构:内存

​ 永久区没有了,JVM调优,PremGenSize,MaxPremGenSize没有了。取而代之,MetaspaceSize,MaxMetaSpaceSize。

  • 代码更少(增加了新的语法 Lambda 表达式)
  • 强大的 Stream API
  • 便于并行
  • 最大化减少空指针异常 Optional

1.Lambda 表达式

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

1-1.从匿名类到Lambda的转换:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//原来的匿名内部类
Runnable ri=new Runnable(){
@Override
public void run(){
System.out.println("sss");
}
};
//现在的 Lambda 表达式
Runnable ri=()->System.out.println("sss");

//原来的匿名内部类作为参数传递
TreeSet<String> ts2 = new TreeSet<>(new Comparator<String>(){
@Override
public int compare(String o1, String o2) {
return Integer.compare(o1.length(), o2.length());
}
});
//现在的 Lambda 表达式作为参数传递
TreeSet<String> ts2 = new TreeSet<>((o1,o2) -> Integer.compare(o1.length(), o2.length());

代码例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//原来的匿名内部类
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);
}

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

1-2.具体例子:

一个实体类,接口,两个实现类,优化方式

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
//实体类
public class Employee {
private int id;
private String name;
private int age;
private double salary;
.....
}
//接口类
public interface MyPredicate<T> {
public boolean test(T t);
}
//实现类
//年龄小于 35
public class FilterEmployeeForAge implements MyPredicate<Employee>{
@Override
public boolean test(Employee t) {
return t.getAge() <= 35;
}
}
//工资大于 5000
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
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
//数组转集合,输入数据
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, "赵六", 8, 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;
}
//测试
@Test
public void test3(){
List<Employee> list = filterEmployeeAge(emps);
for (Employee employee : list) {
System.out.println(employee);
}
}
//如果又多出一个需求
//需求:获取公司中工资大于 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
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
//优化方式一:策略设计模式,使用接口
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;
}
@Test
public void test4(){
//需求1,年龄小于 35
List<Employee> list = filterEmployee(emps, new FilterEmployeeForAge());
for (Employee employee : list) {
System.out.println(employee);
}
System.out.println("------------------------------------------");
//需求2,工资大于 5000
List<Employee> list2 = filterEmployee(emps, new FilterEmployeeForSalary());
for (Employee employee : list2) {
System.out.println(employee);
}
}
//优化方式二:匿名内部类,也是使用接口
@Test
public void test5(){
//需求1,年龄小于 35
List<Employee> list = filterEmployee(emps, new MyPredicate<Employee>() {
@Override
public boolean test(Employee t) {
return t.getAge() <= 35;
}
});
for (Employee employee : list) {
System.out.println(employee);
}
}
//优化方式三:Lambda 表达式
@Test
public void test6(){
//需求1,年龄小于 35
List<Employee> list = filterEmployee(emps, (e) -> e.getAge() <= 35);
list.forEach(System.out::println);

System.out.println("------------------------------------------");
//需求2,工资大于5000
List<Employee> list2 = filterEmployee(emps, (e) -> e.getSalary() >= 5000);
list2.forEach(System.out::println);
}
//优化方式四:Stream API,什么都不用,只要有数据
@Test
public void test7(){
//需求1,年龄小于 35
emps.stream()
.filter((e) -> e.getAge() <= 35)
.forEach(System.out::println);
System.out.println("----------------------------------------------");
//需求2,取出名字,排序sorted,limit前3个
emps.stream()
.map(Employee::getName)
.limit(3)
.sorted()
.forEach(System.out::println);
}

1-3.Lambda表达式的基础介绍

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

  • 左侧:Lambda 表达式的参数列表(接口中抽象方法)
  • 右侧:Lambda 表达式中所需执行的功能, 即 Lambda体。(接口中抽象方法的实现)

1.4.基础语法

  • 语法格式一:无参数,无返回值
    • () -> System.out.println(“Hello Lambda!”);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Test
public void test1(){
int num = 0;
//局部内部类中用了同级别的局部变量时,jdk 1.7 前,必须是 final
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Hello World!" + num);
}
};
r.run();
System.out.println("-------------------------------");

Runnable r1 = () -> System.out.println("Hello Lambda!"+num);
r1.run();
}
  • 语法格式二:有一个参数,并且无返回值
    • (x) -> System.out.println(x)
1
2
3
4
5
@Test
public void test2(){
Consumer<String> con = x -> System.out.println(x);
con.accept("是是是");
}
  • 语法格式三:若只有一个参数,小括号可以省略不写
    • x -> System.out.println(x)
  • 语法格式四:有两个以上的参数,有返回值,并且 Lambda 体中有多条语句
    • Comparator com = (x, y) -> {System.out.println(“函数式接口”);
    • return Integer.compare(x, y);
    • };
1
2
3
4
5
6
7
@Test
public void test3(){
Comparator<Integer> com = (x, y) -> {
System.out.println("函数式接口");
return Integer.compare(x, y);
};
}
  • 语法格式五:若 Lambda 体中只有一条语句, return 和 大括号都可以省略不写
    • Comparator com = (x, y) -> Integer.compare(x, y);
  • 语法格式六:Lambda 表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出,数据类型,即“类型推断”
    • (Integer x, Integer y) -> Integer.compare(x, y);
1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
public void test4(){
//类型推断
Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
}

@Test
public void test5(){
//类型推断
String[] strs = {"aaa", "bbb", "ccc"};
List<String> list = new ArrayList<>();
show(new HashMap<>());
}
  • 左右遇一括号省
  • 左侧推断类型省
  • 能省则省

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

  • 函数式接口:接口中只有一个抽象方法的接口,称为函数式接口。
  • 可以通过 Lambda 表达式来创建该接口的对象。(若 Lambda表达式抛出一个受检异常,那么该异常需要在目标接口的抽象方法上进行声明)。
  • 可以使用注解 @FunctionalInterface 修饰,可以检查它是否是一个函数式接口,同时 javadoc 也会包含一条声明,说明这个接口是一个函数式接口。
1
2
3
4
5
函数式接口中使用泛型
@FunctionalInterface
public interface MyFun<T> {
public T getValue(T t);
}

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

代码:

接口,需求实现方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//只能一个抽象方法,多余一个,报错
@FunctionalInterface
public interface MyFun {
public Integer getValue(Integer num);
}
//需求:对一个数进行运算
@Test
public void test6(){
//对x进行平方
Integer num = operation(100, (x) -> x * x);
System.out.println(num);
//对y进行加200操作
System.out.println(operation(200, (y) -> y + 200));
}
//方法,调用接口
public Integer operation(Integer num, MyFun mf){
return mf.getValue(num);
}

做习题:

2

1.

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, "赵六", 8, 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 emp : emps) {
System.out.println(emp);
}
}

2.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//接口
@FunctionalInterface
public interface MyFunction {
public String getValue(String str);
}
//方法
@Test
public void test2(){
//去除空格
String trimStr = strHandler("\t\t\t 啊啊啊 ", (str) -> str.trim());
System.out.println(trimStr);
//转换大写
String upper = strHandler("abcdef", (str) -> str.toUpperCase());
System.out.println(upper);
//截取字符
String newStr = strHandler("啊啊啊", (str) -> str.substring(2, 5));
System.out.println(newStr);
}
//需求:用于处理字符串
public String strHandler(String str, MyFunction mf){
return mf.getValue(str);
}

3.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//接口
public interface MyFunction2<T, R> {
public R getValue(T t1, T t2);
}
//方法
@Test
public void test3(){
//相加
op(100L, 200L, (x, y) -> x + y);
//相乘
op(100L, 200L, (x, y) -> x * y);
}
//需求:对于两个 Long 型数据进行处理
public void op(Long l1, Long l2, MyFunction2<Long, Long> mf){
System.out.println(mf.getValue(l1, l2));
}

2-2.Java提供接口

3

4

四大内置的四大核心函数式接口:

  • Consumer : 消费型接口
    • void accept(T t);
1
2
3
4
5
6
7
8
9
//Consumer<T> 消费型接口 :
@Test
public void test1(){
happy(10000, (m) -> System.out.println("每次消费:" + m + "元"));
}

public void happy(double money, Consumer<Double> con){
con.accept(money);
}
  • Supplier : 供给型接口
    • T get();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//Supplier<T> 供给型接口 :
@Test
public void test2(){
List<Integer> numList = getNumList(10, () -> (int)(Math.random() * 100));
for (Integer num : numList) {
System.out.println(num);
}
}
//需求:产生指定个数的整数,并放入集合中
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;
}
  • Function<T, R> : 函数型接口
    • R apply(T t);
1
2
3
4
5
6
7
8
9
10
11
12
13
//Function<T, R> 函数型接口:
@Test
public void test3(){
String newStr = strHandler("\t\t\t 我大尚硅谷威武 ", (str) -> str.trim());
System.out.println(newStr);

String subStr = strHandler("我大尚硅谷威武", (str) -> str.substring(2, 5));
System.out.println(subStr);
}
//需求:用于处理字符串
public String strHandler(String str, Function<String, String> fun){
return fun.apply(str);
}
  • Predicate : 断言型接口
    • boolean test(T t);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//Predicate<T> 断言型接口:
@Test
public void test4(){
List<String> list = Arrays.asList("Hello", "atguigu", "Lambda", "www", "ok");
List<String> strList = filterStr(list, (s) -> s.length() > 3);
for (String str : strList) {
System.out.println(str);
}
}

//需求:将满足条件的字符串,放入集合中
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;
}

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

3-1.方法引用

​ 若 Lambda 体中的功能,已经有方法提供了实现,可以使用方法引用(可以将方法引用理解为 Lambda 表达式的另外一种表现形式)

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

​ 方法引用:使用操作符 “ ::” 将方法名和对象或类的名字分隔开来。

1
2
3
4
5
6
7
8
9
10
public void test1(){
PrintStream ps = System.out;
Consumer<String> con = (str) -> ps.println(str);
con.accept("Hello World!");
System.out.println("--------------------------------");

Consumer<String> con2 = ps::println;
con2.accept("Hello Java8!");
Consumer<String> con3 = System.out::println;
}

注意:

  • 方法引用所引用的方法的参数列表与返回值类型,需要与函数式接口中抽象方法的参数列表和返回值类型保持一致!

    • 若Lambda 的参数列表的第一个参数,是实例方法的调用者,第二个参数(或无参)是实例方法的参数时,格式: ClassName::MethodName
  • 对象的引用 :: 实例方法名
1
2
3
4
5
6
7
8
9
10
11
//对象的引用 :: 实例方法名
@Test
public void test2(){
Employee emp = new Employee(101, "张三", 18, 9999.99);
Supplier<String> sup = () -> emp.getName();
System.out.println(sup.get());
System.out.println("----------------------------------");

Supplier<String> sup2 = emp::getName;
System.out.println(sup2.get());
}
  • 类名 :: 静态方法名
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//类名 :: 静态方法名
@Test
public void test4(){
Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
System.out.println("-------------------------------------");

Comparator<Integer> com2 = Integer::compare;
}
@Test
public void test3(){
BiFunction<Double, Double, Double> fun = (x, y) -> Math.max(x, y);
System.out.println(fun.apply(1.5, 22.2));
System.out.println("-----------------------------------------");

BiFunction<Double, Double, Double> fun2 = Math::max;
System.out.println(fun2.apply(1.2, 1.5));
}
  • 类名 :: 实例方法名
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//类名 :: 实例方法名
@Test
public void test5(){
BiPredicate<String, String> bp = (x, y) -> x.equals(y);
System.out.println(bp.test("abcde", "abcde"));
System.out.println("-----------------------------------------");

BiPredicate<String, String> bp2 = String::equals;
System.out.println(bp2.test("abc", "abc"));
System.out.println("-----------------------------------------");


Function<Employee, String> fun = (e) -> e.show();
System.out.println(fun.apply(new Employee()));
System.out.println("-----------------------------------------");

Function<Employee, String> fun2 = Employee::show;
System.out.println(fun2.apply(new Employee()));
}

3-2.构造器引用

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

​ 类名 :: new

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//构造器引用
@Test
public void test7(){
Function<String, Employee> fun = Employee::new;
BiFunction<String, Integer, Employee> fun2 = Employee::new;
}

@Test
public void test6(){
Supplier<Employee> sup = () -> new Employee();
System.out.println(sup.get());
System.out.println("------------------------------------");

Supplier<Employee> sup2 = Employee::new;
System.out.println(sup2.get());
}

3-3.数组引用

​ 类型[] :: new;

1
2
3
4
5
6
7
8
9
10
11
12
//数组引用
@Test
public void test8(){
Function<Integer, String[]> fun = (args) -> new String[args];
String[] strs = fun.apply(10);
System.out.println(strs.length);
System.out.println("--------------------------");

Function<Integer, Employee[]> fun2 = Employee[] :: new;
Employee[] emps = fun2.apply(20);
System.out.println(emps.length);
}

4.Stream API

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

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

​ 集合讲的是数据,流讲的是计算

注意:

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

4-1.Stream 的操作三个步骤

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

4-2.创建 Stream

  • Java8 中的 Collection 接口被扩展,提供了两个获取流的方法 :
1
2
default Stream<E> stream() : 返回一个顺序流
default Stream<E> parallelStream() : 返回一个并行流
  • Java8 中的 Arrays 的静态方法 stream() 可以获取数组流
    1
    static <T> Stream<T> stream(T[] array): 返回一个流
    • 重载形式,能够处理对应基本类型的数组
1
2
3
public static IntStream stream(int[] array)
public static LongStream stream(long[] array)
public static DoubleStream stream(double[] array)
  • 可以使用静态方法 Stream.of(), 通过显示值创建一个流。它可以接收任意数量的参数
1
public static<T> Stream<T> of(T... values) : 返回一个流
  • 可以使用静态方法 Stream.iterate() 和Stream.generate(), 创建无限流
1
2
3
4
//迭代
public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f)
//生成
public static<T> Stream<T> generate(Supplier<T> s) :

例子: Collection 接口,由数组创建流,由值创建流,由函数创建流:创建无限流

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//1. 创建 Stream
@Test
public void test1(){
//1. Collection 提供了两个方法 stream() 与 parallelStream()
List<String> list = new ArrayList<>();
Stream<String> stream = list.stream(); //获取一个顺序流
Stream<String> parallelStream = list.parallelStream(); //获取一个并行流

//2. 通过 Arrays 中的 stream() 获取一个数组流
Integer[] nums = new Integer[10];
Stream<Integer> stream1 = Arrays.stream(nums);

//3. 通过 Stream 类中静态方法 of()
Stream<Integer> stream2 = Stream.of(1,2,3,4,5,6);

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

//生成
Stream<Double> stream4 = Stream.generate(Math::random).limit(2);
stream4.forEach(System.out::println);
}

4-3.Stream 的中间操作

​ 多个 中间操作可以连接起来形成一个 流水线,除非流水线上触发终止操作,否则 中间操作不会执行任何的处理。

​ 而在终止操作时一次性全部 处理,称为“惰性求值”

方法:筛选与切片,映射,排序

筛选与切片

5

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
//2. 中间操作
List<Employee> emps = Arrays.asList(
new Employee(102, "李四", 59, 6666.66),
new Employee(101, "张三", 18, 9999.99),
new Employee(103, "王五", 28, 3333.33),
new Employee(104, "赵六", 8, 7777.77),
new Employee(104, "赵六", 8, 7777.77),
new Employee(104, "赵六", 8, 7777.77),
new Employee(105, "田七", 38, 5555.55)
);
/*
筛选与切片
filter——接收 Lambda , 从流中排除某些元素。
limit——截断流,使其元素不超过给定数量。
skip(n) —— 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
distinct——筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素(要在实体类里重写方法 hashCode() 和 equals())
*/

//内部迭代:迭代操作 Stream API 内部完成
@Test
public void test2(){
//所有的中间操作不会做任何的处理
Stream<Employee> stream = emps.stream()
.filter((e) -> {
System.out.println("测试中间操作");
return e.getAge() <= 35;
});

//只有当做终止操作时,所有的中间操作会一次性的全部执行,称为“惰性求值”
stream.forEach(System.out::println);
}

//外部迭代
@Test
public void test3(){
Iterator<Employee> it = emps.iterator();

while(it.hasNext()){
System.out.println(it.next());
}
}
//filter——接收 Lambda , 从流中排除某些元素。
//limit——截断流,使其元素不超过给定数量。
@Test
public void test4(){
emps.stream()
.filter((e) -> {
System.out.println("短路!"); // && ||
return e.getSalary() >= 5000;
}).limit(3)
.forEach(System.out::println);
}
//skip(n) —— 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
@Test
public void test5(){
emps.parallelStream()
.filter((e) -> e.getSalary() >= 5000)
.skip(2)
.forEach(System.out::println);
}
//distinct——筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素
//要在实体类里重写方法 hashCode() 和 equals()
@Test
public void test6(){
emps.stream()
.distinct()
.forEach(System.out::println);
}

映射

6

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
/*
映射
map——接收 Lambda , 将元素转换成其他形式或提取信息。接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
flatMap——接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流
类似add(Object ob),addAll(Collection coll)
*/
@Test
public void test1(){
Stream<String> str = emps.stream()
.map((e) -> e.getName());
System.out.println("-------------------------------------------");

List<String> strList = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");
Stream<String> stream = strList.stream()
.map(String::toUpperCase);
stream.forEach(System.out::println);
//map 使用方法filterCharacter
Stream<Stream<Character>> stream2 = strList.stream()
.map(TestStreamAPI1::filterCharacter);
//{a,a,a},{b,b,b},流放在流中
stream2.forEach((sm) -> {
sm.forEach(System.out::println);
});
System.out.println("---------------------------------------------");
//flatMap 使用方法filterCharacter
Stream<Character> stream3 = strList.stream()
.flatMap(TestStreamAPI1::filterCharacter);
//a,a,a,b,b,b,元素放在流中
stream3.forEach(System.out::println);
}

public static Stream<Character> filterCharacter(String str){
List<Character> list = new ArrayList<>();
//Str转字符串数组
for (Character ch : str.toCharArray()) {
list.add(ch);
}
return list.stream();
}

排序

7

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*
sorted()——自然排序(Comparable)
sorted(Comparator com)——定制排序(Compatator)
*/
@Test
public void test2(){
//对名字排序
emps.stream()
.map(Employee::getName)
.sorted()
.forEach(System.out::println);
System.out.println("------------------------------------");
//对年龄和名字进行排序
emps.stream()
.sorted((x, y) -> {
if(x.getAge() == y.getAge()){
return x.getName().compareTo(y.getName());
}else{
return Integer.compare(x.getAge(), y.getAge());
}
}).forEach(System.out::println);
}

4-4.Stream 的终止操作

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

方法:

查找与匹配

8

9

实体类加个方法:

1
2
3
4
5
6
7
8
9
10
11
public class Employee {
private int id;
private String name;
private int age;
private double salary;
private Status status;
...
public enum Status {
FREE, BUSY, VOCATION;
}
}

测试类:

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
public class TestStreamAPI2 {
List<Employee> emps = Arrays.asList(
new Employee(102, "李四", 59, 6666.66, Status.BUSY),
new Employee(101, "张三", 18, 9999.99, Status.FREE),
new Employee(103, "王五", 28, 3333.33, Status.VOCATION),
new Employee(104, "赵六", 8, 7777.77, Status.BUSY),
new Employee(104, "赵六", 8, 7777.77, Status.FREE),
new Employee(104, "赵六", 8, 7777.77, Status.FREE),
new Employee(105, "田七", 38, 5555.55, Status.BUSY)
);
//3. 终止操作
/*
allMatch——检查是否匹配所有元素
anyMatch——检查是否至少匹配一个元素
noneMatch——检查是否没有匹配的元素
findFirst——返回第一个元素
findAny——返回当前流中的任意元素
count——返回流中元素的总个数
max——返回流中最大值
min——返回流中最小值
*/
@Test
public void test1(){
//allMatch——检查是否匹配所有元素
boolean bl = emps.stream()
.allMatch((e) -> e.getStatus().equals(Status.BUSY));
System.out.println(bl);

//anyMatch——检查是否至少匹配一个元素
boolean bl1 = emps.stream()
.anyMatch((e) -> e.getStatus().equals(Status.BUSY));
System.out.println(bl1);

//noneMatch——检查是否没有匹配的元素
boolean bl2 = emps.stream()
.noneMatch((e) -> e.getStatus().equals(Status.BUSY));
System.out.println(bl2);
}

@Test
public void test2(){
//findFirst——返回第一个元素
//对工资进行排序,找第一个,有可能没有数据,没有第一个
//Optional,避免空指针异常,容器类,有个orElse方法,对象为空,找个替代的对象
Optional<Employee> op = emps.stream()
.sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()))
.findFirst();
System.out.println(op.get());
System.out.println("--------------------------------");

//findAny——返回当前流中的任意元素
Optional<Employee> op2 = emps.parallelStream()
.filter((e) -> e.getStatus().equals(Status.FREE))
.findAny();
System.out.println(op2.get());
}

@Test
public void test3(){
//count——返回流中元素的总个数
long count = emps.stream()
.filter((e) -> e.getStatus().equals(Status.FREE))
.count();
System.out.println(count);

//max——返回流中最大值
Optional<Double> op = emps.stream()
.map(Employee::getSalary)
.max(Double::compare);
System.out.println(op.get());

//min——返回流中最小值
Optional<Employee> op2 = emps.stream()
.min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
System.out.println(op2.get());
}

//注意:流进行了终止操作后,不能再次使用
@Test
public void test4(){
//查找FREE
Stream<Employee> stream = emps.stream()
.filter((e) -> e.getStatus().equals(Status.FREE));
//统计总数
long count = stream.count();
//提取getSalary,找工资最大值
stream.map(Employee::getSalary)
.max(Double::compare);
}
}

归约::map 和 reduce 的连接通常称为 map-reduce 模式

10

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
/*
归约
reduce(T identity, BinaryOperator)
reduce(BinaryOperator) ——可以将流中元素反复结合起来,得到一个值。
*/
@Test
public void test1(){
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
//sum,累加
Integer sum = list.stream()
.reduce(0, (x, y) -> x + y);
System.out.println(sum);
System.out.println("----------------------------------------");
//提取工资,累加
Optional<Double> op = emps.stream()
.map(Employee::getSalary)
.reduce(Double::sum);
System.out.println(op.get());
}
//收集的例子
@Test
public void test2(){
Optional<Double> sum = emps.stream()
.map(Employee::getSalary)
.collect(Collectors.reducing(Double::sum));
System.out.println(sum.get());
}
//需求:搜索名字中 “六” 出现的次数
@Test
public void test2(){
Optional<Integer> sum = emps.stream()
.map(Employee::getName)
.flatMap(TestStreamAPI1::filterCharacter)
.map((ch) -> {
if(ch.equals('六'))
return 1;
else
return 0;
}).reduce(Integer::sum);

System.out.println(sum.get());
}

收集

11

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

12

13

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
//collect——将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法
@Test
public void test3(){
//元素收集到list
List<String> list = emps.stream()
.map(Employee::getName)
.collect(Collectors.toList());
list.forEach(System.out::println);
System.out.println("----------------------------------");

//元素收集到set
Set<String> set = emps.stream()
.map(Employee::getName)
.collect(Collectors.toSet());
set.forEach(System.out::println);
System.out.println("----------------------------------");

//元素收集到HashSet
HashSet<String> hs = emps.stream()
.map(Employee::getName)
.collect(Collectors.toCollection(HashSet::new));
hs.forEach(System.out::println);
}

@Test
public void test4(){
//最大值
Optional<Double> min = emps.stream()
.map(Employee::getSalary)
.collect(Collectors.minBy(Double::compare));
System.out.println(min.get());

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

//总和
Double sum = emps.stream()
.collect(Collectors.summingDouble(Employee::getSalary));
System.out.println(sum);

//平均值
Double avg = emps.stream()
.collect(Collectors.averagingDouble(Employee::getSalary));
System.out.println(avg);

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

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

//一次性得到要搞该元素的个数、总和、均值、最大值、最小值
DoubleSummaryStatistics dss = emps.stream()
.collect(Collectors.summarizingDouble(Employee::getSalary));
System.out.println(dss);
System.out.println(dss.getMax());
}

//分组
@Test
public void test5(){
Map<Status, List<Employee>> map = emps.stream()
.collect(Collectors.groupingBy(Employee::getStatus));
System.out.println(map);
}

//多级分组
@Test
public void test6(){
Map<Status, Map<String, List<Employee>>> map = emps.stream()
.collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> {
if(e.getAge() >= 60)
return "老年";
else if(e.getAge() >= 35)
return "中年";
else
return "成年";
})));
System.out.println(map);
}

//分区,对或错
@Test
public void test7(){
Map<Boolean, List<Employee>> map = emps.stream()
.collect(Collectors.partitioningBy((e) -> e.getSalary() >= 5000));
System.out.println(map);
}

//字符串加,首尾加"----"
@Test
public void test8(){
String str = emps.stream()
.map(Employee::getName)
.collect(Collectors.joining("," , "----", "----"));
System.out.println(str);
}

4-5.练习题

Stream

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
/*
1. 给定一个数字列表,如何返回一个由每个数的平方构成的列表呢?
给定【1,2,3,4,5】, 应该返回【1,4,9,16,25】。
*/
@Test
public void test1(){
Integer[] nums = new Integer[]{1,2,3,4,5};

Arrays.stream(nums)
.map((x) -> x * x)
.forEach(System.out::println);
}

/*
2. 怎样用 map 和 reduce 方法数一数流中有多少个Employee呢?
*/
List<Employee> emps = Arrays.asList(
new Employee(102, "李四", 59, 6666.66, Status.BUSY),
new Employee(101, "张三", 18, 9999.99, Status.FREE),
new Employee(103, "王五", 28, 3333.33, Status.VOCATION),
new Employee(104, "赵六", 8, 7777.77, Status.BUSY),
new Employee(104, "赵六", 8, 7777.77, Status.FREE),
new Employee(104, "赵六", 8, 7777.77, Status.FREE),
new Employee(105, "田七", 38, 5555.55, Status.BUSY)
);

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

综合例子:实体类,解决问题类

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
119
120
121
//交易员类
public class Trader {
private String name;
private String city;
.....
}
//交易类
public class Transaction {
private Trader trader;
private int year;
private int value;
....
}
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((t1, t2) -> Integer.compare(t1.getValue(), t2.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().equals("Cambridge"))
.map(Transaction::getTrader)
.sorted((t1, t2) -> t1.getName().compareTo(t2.getName()))
.distinct()
.forEach(System.out::println);
}
//4. 返回所有交易员的姓名字符串,按字母顺序排序
@Test
public void test4(){
transactions.stream()
.map((t) -> t.getTrader().getName())
.sorted()
.forEach(System.out::println);
System.out.println("-----------------------------------");
//String的排序
String str = transactions.stream()
.map((t) -> t.getTrader().getName())
.sorted()
.reduce("", String::concat);
System.out.println(str);
System.out.println("------------------------------------");
//按字母大小写排序,调用方法
transactions.stream()
.map((t) -> t.getTrader().getName())
.flatMap(TestTransaction::filterCharacter)
.sorted((s1, s2) -> s1.compareToIgnoreCase(s2))
.forEach(System.out::print);
}

public static Stream<String> filterCharacter(String str){
List<String> list = new ArrayList<>();
for (Character ch : str.toCharArray()) {
list.add(ch.toString());
}
return list.stream();
}
//5. 有没有交易员是在米兰工作的?
@Test
public void test5(){
boolean bl = transactions.stream()
.anyMatch((t) -> t.getTrader().getCity().equals("Milan"));
System.out.println(bl);
}
//6. 打印生活在剑桥的交易员的所有交易额
@Test
public void test6(){
Optional<Integer> sum = transactions.stream()
.filter((e) -> e.getTrader().getCity().equals("Cambridge"))
.map(Transaction::getValue)
.reduce(Integer::sum);
System.out.println(sum.get());
}
//7. 所有交易中,最高的交易额是多少
@Test
public void test7(){
Optional<Integer> max = transactions.stream()
.map((t) -> t.getValue())
.max(Integer::compare);
System.out.println(max.get());
}
//8. 找到交易额最小的交易
@Test
public void test8(){
Optional<Transaction> op = transactions.stream()
.min((t1, t2) -> Integer.compare(t1.getValue(), t2.getValue()));
System.out.println(op.get());
}
}

5.并行流与串行流

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

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

Fork/Join 框架

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

14

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

采用 “工作窃取”模式(work-stealing):

​ 当执行新的任务时它可以将其拆分分成更小的任务执行,并将小任务加到线程队列中,然后再从一个随机线程的队列中偷一个并把它放在自己的队列中。

​ 相对于一般的线程池实现,fork/join框架的优势体现在对其中包含的任务的处理方式上。在一般的线程池中,如果一个线程正在执行的任务由于某些原因无法继续运行,那么该线程会处于等待状态。

​ 而在fork/join框架实现中,如果某个子问题由于等待另外一个子问题的完成而无法继续运行。那么处理该子问题的线程会主动寻找其他尚未运行的子问题来执行,这种方式减少了线程的等待时间,提高了性能 。

ForkJoin框架

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
public class ForkJoinCalculate extends RecursiveTask<Long>{
/**
* 序列化
*/
private static final long serialVersionUID = 13475679780L;
//拆分
private long start;
private long end;
//临界值
private static final long THRESHOLD = 10000L;

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(start, middle);
left.fork();
//拆分,并将该子任务压入线程队列
ForkJoinCalculate right = new ForkJoinCalculate(middle+1, end);
right.fork();
//合并,累加总和
return left.join() + right.join();
}
}
}

测试类:

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
public class TestForkJoin {
/*
* ForkJoin框架
*/
@Test
public void test1(){
long start = System.currentTimeMillis();
//线程池支持
ForkJoinPool pool = new ForkJoinPool();
ForkJoinTask<Long> task = new ForkJoinCalculate(0L, 10000000000L);
long sum = pool.invoke(task);
System.out.println(sum);
long end = System.currentTimeMillis();
System.out.println("耗费的时间为: " + (end - start));
//112-1953-1988-2654-2647-20663-113808
}
/*
* 普通for
*/
@Test
public void test2(){
long start = System.currentTimeMillis();
long sum = 0L;
for (long i = 0L; i <= 10000000000L; i++) {
sum += i;
}
System.out.println(sum);
long end = System.currentTimeMillis();
System.out.println("耗费的时间为: " + (end - start));
//34-3174-3132-4227-4223-31583
}
/*
* java8并行流
*/
@Test
public void test3(){
long start = System.currentTimeMillis();
//reduce(0,Long::sum)顺序流
Long sum = LongStream.rangeClosed(0L, 10000000000L)
.parallel()
.sum();
System.out.println(sum);
long end = System.currentTimeMillis();
System.out.println("耗费的时间为: " + (end - start));
//2061-2053-2086-18926
}
}

6.Optional 类

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

常用方法:

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

Optional 容器类:用于尽量避免空指针异常

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
/*
* Optional.of(T t) : 创建一个 Optional 实例
* Optional.empty() : 创建一个空的 Optional 实例
* Optional.ofNullable(T t):若 t 不为 null,创建 Optional 实例,否则创建空实例
* isPresent() : 判断是否包含值
* orElse(T t) : 如果调用对象包含值,返回该值,否则返回t
* orElseGet(Supplier s) :如果调用对象包含值,返回该值,否则返回 s 获取的值
* map(Function f): 如果有值对其处理,并返回处理后的Optional,否则返回 Optional.empty()
* flatMap(Function mapper):与 map 类似,要求返回值必须是Optional
*/
public class TestOptional {
@Test
public void test4(){
Optional<Employee> op = Optional.of(new Employee(101, "张三", 18, 9999.99));
//如果有值对其处理,并返回处理后的Optional,否则返回 Optional.empty()
Optional<String> op2 = op.map(Employee::getName);
System.out.println(op2.get());
//与 map 类似,要求返回值必须是Optional
Optional<String> op3 = op.flatMap((e) -> Optional.of(e.getName()));
System.out.println(op3.get());
}

@Test
public void test3(){
//若 t 不为 null,创建 Optional 实例,否则创建空实例
Optional<Employee> op = Optional.ofNullable(new Employee());
//判断是否包含值
if(op.isPresent()){
System.out.println(op.get());
}
//如果调用对象包含值,返回该值,否则返回t
Employee emp = op.orElse(new Employee("张三"));
System.out.println(emp);
//如果调用对象包含值,返回该值,否则返回 s 获取的值
Employee emp2 = op.orElseGet(() -> new Employee());
System.out.println(emp2);
}

@Test
public void test2(){
Optional<Employee> op2 = Optional.ofNullable(null);
//报错
System.out.println(op2.get());
//创建一个空的 Optional 实例
Optional<Employee> op = Optional.empty();
//报错
System.out.println(op.get());
}

@Test
public void test1(){
//创建一个 Optional 实例
//报错
//Optional<Employee> op = Optional.of(null);
Optional<Employee> op = Optional.of(new Employee());
Employee emp = op.get();
System.out.println(emp);
}
}

例题:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//类
public class Man {
private Godness god;
...
}
public class Godness {
private String name;
...
}
//注意:Optional 不能被序列化
public class NewMan {
//有对象在
private Optional<Godness> godness = Optional.empty();
private Godness god;
...
}
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
//例题
@Test
public void test5(){
Man man = new Man();
String name = getGodnessName(man);
System.out.println(name);
}
//需求:获取一个男人心中女神的名字
public String getGodnessName(Man man){
//避免空指针异常
if(man != null){
Godness g = man.getGod();
if(g != null){
return g.getName();
}
}
return "没有这个人";
}

//运用 Optional 的实体类
@Test
public void test6(){
Optional<Godness> godness = Optional.ofNullable(new Godness("林志玲"));
Optional<NewMan> op = Optional.ofNullable(new NewMan(godness));
String name = getGodnessName2(op);
System.out.println(name);
}
public String getGodnessName2(Optional<NewMan> man){
//保证一定有个对象
return man.orElse(new NewMan())
.getGodness()
.orElse(new Godness("没有这个人"))
.getName();
}

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

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

如下面:MyFun

1
2
3
4
5
public interface MyFun {
default String getName(){
return "哈哈哈";
}
}

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

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

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

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

例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public interface MyFun {
default String getName(){
return "哈哈哈";
}
}
public class MyClass {
public String getName(){
return "嘿嘿嘿";
}
}
public interface MyInterface {
default String getName(){
return "呵呵呵";
}
//静态方法
public static void show(){
System.out.println("接口中的静态方法");
}
}

测试类:****

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class SubClass extends MyClass implements MyFun{
@Override
public String getName() {
return super.getName();
}

}
public class SubClass2 implements MyFun, MyInterface{
@Override
public String getName() {
return MyInterface.super.getName();
}

}
public class TestDefaultInterface {
public static void main(String[] args) {
SubClass sc = new SubClass();
System.out.println(sc.getName());
//静态方法
MyInterface.show();
}
}

8.新时间日期 API

例子:

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
//调用的方法
public class DateFormatThreadLocal {
private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>(){
protected DateFormat initialValue(){
return new SimpleDateFormat("yyyyMMdd");
}
};
public static final Date convert(String source) throws ParseException{
return df.get().parse(source);
}
}
public class TestSimpleDateFormat {
public static void main(String[] args) throws Exception {
/*
//线程问题
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//需要一个实例
Callable<Date> task = new Callable<Date>() {
@Override
public Date call() throws Exception {
return sdf.parse("20161121");
}
};
//线程池,长度为10
ExecutorService pool = Executors.newFixedThreadPool(10);
//返回结果放在list
List<Future<Date>> results = new ArrayList<>();
for (int i = 0; i < 10; i++) {
results.add(pool.submit(task));
}

for (Future<Date> future : results) {
System.out.println(future.get());
}
pool.shutdown();
*/
//解决多线程安全问题
/*
Callable<Date> task = new Callable<Date>() {
@Override
public Date call() throws Exception {
return DateFormatThreadLocal.convert("20161121");
}
};
ExecutorService pool = Executors.newFixedThreadPool(10);
List<Future<Date>> results = new ArrayList<>();
for (int i = 0; i < 10; i++) {
results.add(pool.submit(task));
}
for (Future<Date> future : results) {
System.out.println(future.get());
}
pool.shutdown();
*/
//java8
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
Callable<LocalDate> task = new Callable<LocalDate>() {
@Override
public LocalDate call() throws Exception {
LocalDate ld = LocalDate.parse("20161121", dtf);
return ld;
}
};
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();
}
}

8-1.使用 LocalDate 、LocalTime 、LocalDateTime

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

15

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//1. LocalDate、LocalTime、LocalDateTime
@Test
public void test1(){
//获取当前时间
LocalDateTime ldt = LocalDateTime.now();
System.out.println(ldt);
//设置时间
LocalDateTime ld2 = LocalDateTime.of(2016, 11, 21, 10, 10, 10);
System.out.println(ld2);
//加年
LocalDateTime ldt3 = ld2.plusYears(20);
System.out.println(ldt3);
//减时间
LocalDateTime ldt4 = ld2.minusMonths(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());
}

8-2.Instant

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//2. Instant : 时间戳。 (使用 Unix 元年  1970年1月1日 00:00:00 所经历的毫秒值)
@Test
public void test2(){
Instant ins = Instant.now();
//默认使用 UTC 时区
System.out.println(ins);
//添加时间
OffsetDateTime odt = ins.atOffset(ZoneOffset.ofHours(8));
System.out.println(odt);
//从第二个开始的时间线获取纳米秒数
System.out.println(ins.getNano());
//加5秒,原始时间
Instant ins2 = Instant.ofEpochSecond(5);
System.out.println(ins2);
}

8-3.Duration 和 Period

  • Duration:用于计算两个“时间”间隔
  • Period:用于计算两个“日期”间隔
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//Duration : 用于计算两个“时间”间隔
//Period : 用于计算两个“日期”间隔
@Test
public void test3(){
Instant ins1 = Instant.now();
System.out.println("--------------------");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
Instant ins2 = Instant.now();
System.out.println("所耗费时间为:" + Duration.between(ins1, ins2));
//获取毫秒 Duration.toMillis()
System.out.println("----------------------------------");

LocalDate ld1 = LocalDate.now();
LocalDate ld2 = LocalDate.of(2011, 1, 1);
Period pe = Period.between(ld2, ld1);
System.out.println(pe.getYears());
System.out.println(pe.getMonths());
System.out.println(pe.getDays());
}

8-4.日期的操纵

  • TemporalAdjuster : 时间校正器。有时我们可能需要获取例如:将日期调整到“下个周日”等操作。
  • TemporalAdjusters : 该类通过静态方法提供了大量的常
    用 TemporalAdjuster 的实现。
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
//4. TemporalAdjuster : 时间校正器
@Test
public void test4(){
LocalDateTime ldt = LocalDateTime.now();
System.out.println(ldt);

LocalDateTime ldt2 = ldt.withDayOfMonth(10);
System.out.println(ldt2);
//增加下一周
LocalDateTime ldt3 = ldt.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
System.out.println(ldt3);
//自定义:下一个工作日
LocalDateTime ldt5 = ldt.with((l) -> {
LocalDateTime ldt4 = (LocalDateTime) l;
DayOfWeek dow = ldt4.getDayOfWeek();
//周五加3天,周六加2天,周日加一天
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);
}

8-5.解析与格式化

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

  • 预定义的标准格式
  • 语言环境相关的格式
  • 自定义的格式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//5. DateTimeFormatter : 解析和格式化日期或时间
@Test
public void test5(){
//提供的时间格式
//DateTimeFormatter dtf = DateTimeFormatter.ISO_LOCAL_DATE;
//自定义时间格式
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss E");
LocalDateTime ldt = LocalDateTime.now();
String strDate = ldt.format(dtf);
System.out.println(strDate);
//将字符串转换为时间
LocalDateTime newLdt = ldt.parse(strDate, dtf);
System.out.println(newLdt);
}

8-6.时区的处理

​ 带时区的时间为分别为:ZonedDate、ZonedTime、ZonedDateTime

​ 其中每个时区都对应着 ID,地区ID都为 “{区域}/{城市}”的格式

​ 例如 :Asia/Shanghai 等

  • ZoneId:该类中包含了所有的时区信息
    • getAvailableZoneIds() : 可以获取所有时区时区信息
    • of(id) : 用指定的时区信息获取 ZoneId 对象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//6.ZonedDate、ZonedTime、ZonedDateTime : 带时区的时间或日期
@Test
public void test7(){
//指定时区Asia/Shanghai
LocalDateTime ldt = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
System.out.println(ldt);
//指定时区US/Pacific
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("US/Pacific"));
System.out.println(zdt);
}
@Test
public void test6(){
//获取所有时区
Set<String> set = ZoneId.getAvailableZoneIds();
set.forEach(System.out::println);
}

8-7.与传统日期处理的转换

16

9.重复注解与类型注解

​ Java 8对注解处理:可重复的注解及可用于类型的注解

1
2
3
4
5
6
7
8
9
10
11
12
13
//类型注解 TYPE_PARAMETER
@Repeatable(MyAnnotations.class)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE,TYPE_PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String value() default "atguigu";
}

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

测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*
* 重复注解与类型注解
*/
public class TestAnnotation {
@Test
public void test1() throws Exception {
Class<TestAnnotation> clazz=TestAnnotation.class;
Method m1=clazz.getMethod("show");
MyAnnotation[] max=m1.getAnnotationsByType(MyAnnotation.class);
for (MyAnnotation myAnnotation : max) {
System.out.println(myAnnotation.value());
}
}
@MyAnnotation("Hello")
@MyAnnotation("World")
public void show(String str){
}
@MyAnnotation("Hello")
@MyAnnotation("World")
public void show2(@MyAnnotation("abd") String str){
}
}
-------------本文结束感谢您的阅读-------------

本文标题:java8新特性

文章作者:Linhuide

发布时间:2020年03月26日 - 00:03

最后更新:2020年04月05日 - 15:04

原始链接:https://linhuide.github.io/post/f41870e2.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

坚持原创技术分享,您的支持将鼓励我继续创作!