java8 新特性(下)

👑 博主简介:知名开发工程师
👣 出没地点:北京
💊 2023年目标:成为一个大佬
———————————————————————————————————————————
版权声明:本文为原创文章,如需转载须注明出处,喜欢可收藏!

一. Stream API

当我们在需要对集合中的元素进行操作的时候,除了必需的添加,删除,获取外,最典型的操作就是集合遍历。不同的需求总是一次次的循环循环循环。这时我们希望有更加高效的处理方式,这时我们就可以通过JDK8中提供的Stream API来解决这个问题了。

public static void main(String[] args) {
    // 定义一个List集合
    List<String> list = Arrays.asList("张三", "张三丰", "成龙", "周星驰");
    // 1.获取所有 姓张的信息
    // 2.获取名称长度为3的用户
    // 3. 输出所有的用户信息
    System.out.println("----------");
    list.stream()
            .filter(s -> s.startsWith("张"))
            .filter(s -> s.length() == 3)
            .forEach(System.out::println);
}

更加的简洁直观

1. Steam流式思想概述

注意:Stream和IO流(InputStream/OutputStream)没有任何关系,请暂时忘记对传统IO流的固有印象!

Stream流式思想类似于工厂车间的“生产流水线”,Stream流不是一种数据结构,不保存数据,而是对数据进行加工处理。Stream可以看作是流水线上的一个工序。在流水线上,通过多个工序让一个原材料加工成一个商 品。

2. Stream流的获取方式

根据Collection获取

首先,java.util.Collection 接口中加入了default方法 stream,也就是说Collection接口下的所有的实现都可以通过steam方法来获取Stream流。

List<String> list = new ArrayList<>();
list.stream();
Set<String> set = new HashSet<>();
set.stream();
Vector vector = new Vector();
vector.stream();

但是Map接口别没有实现Collection接口,那这时怎么办呢?这时我们可以根据Map获取对应的key value的集合。

Map<String,Object> map = new HashMap<>();
Stream<String> stream = map.keySet().stream(); // key
Stream<Object> stream1 = map.values().stream(); // value
Stream<Map.Entry<String, Object>> stream2 = map.entrySet().stream(); // entry

通过Stream的of方法

在实际开发中我们不可避免的还是会操作到数组中的数据,由于数组对象不可能添加默认方法,所有Stream接口中提供了静态方法of

Stream<String> a1 = Stream.of("a1", "a2", "a3");

String[] arr1 = {"aa","bb","cc"};
Stream<String> arr11 = Stream.of(arr1);

Integer[] arr2 = {1,2,3,4};
Stream<Integer> arr21 = Stream.of(arr2);

arr21.forEach(System.out::println); //1  2  3  4
// 注意:基本数据类型的数组是不行的
int[] arr3 = {1,2,3,4};
Stream.of(arr3).forEach(System.out::println); //[I@57829d67

3. Stream常用方法介绍

方法名方法作用返回值类型方法种类
count统计个数long终结
forEach逐一处理void终结
filter过滤Stream函数拼接
limit取用前几个Stream函数拼接
skip跳过前几个Stream函数拼接函数拼接
map映射Stream函数拼接
concat组合Stream函数拼接

Stream流模型的操作很丰富,这里介绍一些常用的API。这些方法可以被分成两种:

**终结方法:**返回值类型不再是 Stream 类型的方法,不再支持链式调用。本小节中,终结方法包括 count 和 forEach 方法。

**非终结方法:**返回值类型仍然是 Stream 类型的方法,支持链式调用。

Stream注意事项(重要)

  1. Stream只能操作一次
  2. Stream方法返回的是新的流
  3. Stream不调用终结方法,中间的操作不会执行

1. forEach

forEach用来遍历流中的数据的,该方法接受一个Consumer接口,会将每一个流元素交给函数处理

Stream.of("a1", "a2", "a3").forEach(System.out::println);

2. count

Stream流中的count方法用来统计其中的元素个数的

long count = Stream.of("a1", "a2", "a3").count();

3. filter

filter方法的作用是用来过滤数据的,返回符合条件的数据。该接口接收一个Predicate函数式接口参数作为筛选条件。

Stream.of("a1", "a2", "a3","bb","cc","aa","dd")
        .filter((s)->s.contains("a"))
        .forEach(System.out::println); //a1  a2  a3  a4

4. limit

limit方法可以对流进行截取处理,支取前n个数据,参数是一个long类型的数值,如果集合当前长度大于参数就进行截取,否则不操作:

Stream.of("a1", "a2", "a3","bb","cc","aa","dd")
        .limit(3)
        .forEach(System.out::println); //a1  a2  a3

5. skip

如果希望跳过前面几个元素,可以使用skip方法获取一个截取之后的新流:

Stream.of("a1", "a2", "a3","bb","cc","aa","dd")
        .skip(3)
        .forEach(System.out::println); // bb cc aa dd

6. map

如果我们需要将流中的元素映射到另一个流中,可以使用map方法

Stream.of("1", "2", "3", "4", "5", "6", "7")
        //.map(msg->Integer.parseInt(msg))
        .map(Integer::parseInt)
        .forEach(System.out::println);

7. sorted

如果需要将数据排序,可以使用sorted方法:在使用的时候可以根据自然规则排序,也可以通过比较强来指定对应的排序规则

Stream.of("1", "3", "2", "4", "0", "9", "7")
                //.map(msg->Integer.parseInt(msg))
                .map(Integer::parseInt)
                .sorted()
                .forEach(System.out::println); // 根据数据的自然顺序排序

8. distinct

如果要去掉重复数据,可以使用distinct方法:

Stream.of("1", "3", "3", "4", "0", "1", "7")
        .map(Integer::parseInt)
        .sorted((o1, o2) -> o2 - o1) // 降序
        .distinct() // 去掉重复的记录
        .forEach(System.out::println);

9. match

如果需要判断数据是否匹配指定的条件,可以使用match相关的方法

boolean anyMatch(Predicate<? super T> predicate); // 元素是否有任意一个满足条件
boolean allMatch(Predicate<? super T> predicate); // 元素是否都满足条件
boolean noneMatch(Predicate<? super T> predicate); // 元素是否都不满足条件
boolean b = Stream.of("1", "3", "3", "4", "5", "1", "7")
        .map(Integer::parseInt)
        //.allMatch(s -> s > 0)
        //.anyMatch(s -> s >4)
        .noneMatch(s -> s > 4);
System.out.println(b); // false

10. find

如果我们需要找到某些数据,可以使用find方法来实现

Optional<T> findFirst(); //返回列表中的第一个元素。
Optional<T> findAny(); //返回的元素是不确定的,返回当前流中的任意元素。
Optional<String> first = Stream.of("1", "3", "3", "4", "5", "1", "7").findFirst()
System.out.println(first.get());

Optional<String> any = Stream.of("1", "3", "3", "4", "5", "1", "7").findAny();
System.out.println(any.get());

findAny()是为了更高效的性能。如果是数据较少,串行地情况下,一般会返回第一个结果,如果是并行 的情况,那就不能确保是第一个。比如下面的例子会随机地返回OptionalInt[50]。

System.out.println(IntStream.range(0, 100).parallel().findAny());

11. max和min

如果我们想要获取最大值和最小值,那么可以使用max和min方法

Optional<Integer> max = Stream.of("1", "3", "3", "4", "5", "1", "7")
        .map(Integer::parseInt)
        .max((o1,o2)->o1-o2); // 7
System.out.println(max.get());
Optional<Integer> min = Stream.of("1", "3", "3", "4", "5", "1", "7")
        .map(Integer::parseInt)
        .min((o1,o2)->o1-o2);
System.out.println(min.get()); // 1

12. reduce方法

如果需要将所有数据归纳得到一个数据,可以使用reduce方法

T reduce(T identity, BinaryOperator accumulator);
// identity默认值
// 第一次的时候会将默认值赋值给x
// 之后每次会将 上一次的操作结果赋值给x y就是每次从数据中获取的元素
Integer sum = Stream.of(4, 5, 3, 9)
        .reduce(0, (x, y) -> {
            System.out.println("x=" + x + ",y=" + 
            return x + y;
        });
System.out.println(sum); // 21
// 获取 最大值
Integer max = Stream.of(4, 5, 3, 9)
        .reduce(0, (x, y) -> {
            return x > y ? x : y;
        });
System.out.println(max); // 9

13. map和reduce的组合

在实际开发中我们经常会将map和reduce一块来使用

// 1.求出所有年龄的总和
Integer sumAge = Stream.of(
                new Person("张三", 18)
                , new Person("李四", 22)
                , new Person("张三", 13)
                , new Person("王五", 15)
                , new Person("张三", 19)
        ).map(Person::getAge) // 实现数据类型的转换
        .reduce(0, Integer::sum);
System.out.println(sumAge); // 87

// 2.求出所有年龄中的最大值
Integer maxAge = Stream.of(
                new Person("张三", 18)
                , new Person("李四", 22)
                , new Person("张三", 13)
                , new Person("王五", 15)
                , new Person("张三", 19)
        ).map(Person::getAge) // 实现数据类型的转换,符合reduce对数据的要求
        .reduce(0, Math::max); // reduce实现数据的处理
System.out.println(maxAge); // 22

// 3.统计 字符 a 出现的次数
Integer count = Stream.of("a", "b", "c", "d", "a", "c", "a")
        .map(ch -> "a".equals(ch) ? 1 : 0)
        .reduce(0, Integer::sum);
System.out.println(count); // 3


class Person {
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public int getAge() {
        return age;
    }
}

14. mapToInt

如果需要将Stream中的Integer类型转换成int类型,可以使用mapToInt方法来实现

// Integer占用的内存比int多很多,在Stream流操作中会自动装修和拆箱操作
Integer arr[] = {1, 2, 3, 5, 6, 8};
Stream.of(arr)
        .filter(i -> i > 0)
        .forEach(System.out::println);
System.out.println("---------");
// 为了提高程序代码的效率,我们可以先将流中Integer数据转换为int数据,然后再操作
IntStream intStream = Stream.of(arr)
        .mapToInt(Integer::intValue);
intStream.filter(i -> i > 3)
        .forEach(System.out::println);

15. concat

如果有两个流,希望合并成为一个流,那么可以使用Stream接口的静态方法concat

Stream<String> stream1 = Stream.of("a","b","c");
Stream<String> stream2 = Stream.of("x", "y", "z");
// 通过concat方法将两个流合并为一个新的流
Stream.concat(stream1,stream2).forEach(System.out::println);

4. 综合案例

定义两个集合,然后在集合中存储多个用户名称,然后完成如下的操作:

  1. 第一个队伍只保留姓名长度为3的成员
  2. 第一个队伍筛选之后只要前3个人
  3. 第二个队伍只要姓张的成员
  4. 第二个队伍筛选之后不要前两个人
  5. 将两个队伍合并为一个队伍
  6. 根据姓名创建Person对象
  7. 打印整个队伍的Person信息
List<String> list1 = Arrays.asList("迪丽热巴", "宋远桥", "苏星河", "老子",
"庄子", "孙子", "洪七 公");
List<String> list2 = Arrays.asList("古力娜扎", "张无忌", "张三丰", "赵丽颖",
"张二狗", "张天爱", "张三");
// 1. 第一个队伍只保留姓名长度为3的成员
// 2. 第一个队伍筛选之后只要前3个人
Stream<String> stream1 = list1.stream().filter(s -> s.length() ==
3).limit(3);
// 3. 第二个队伍只要姓张的成员
// 4. 第二个队伍筛选之后不要前两个人
Stream<String> stream2 = list2.stream().filter(s ->
s.startsWith("张")).skip(2);
// 5. 将两个队伍合并为一个队伍
// 6. 根据姓名创建Person对象
// 7. 打印整个队伍的Person信息
Stream.concat(stream1,stream2)
//.map(n-> new Person(n))
.map(Person::new)
.forEach(System.out::println);

5. Stream结果收集

5.1 结果收集到集合中

List<String> list = Stream.of("aa", "bb", "cc","aa")
        .collect(Collectors.toList());
System.out.println(list);
// 收集到 Set集合中
Set<String> set = Stream.of("aa", "bb", "cc", "aa")
        .collect(Collectors.toSet());
System.out.println(set);
// 如果需要获取的类型为具体的实现,比如:ArrayList HashSet
ArrayList<String> arrayList = Stream.of("aa", "bb", "cc", "aa")
        //.collect(Collectors.toCollection(() -> new ArrayList<>()));
        .collect(Collectors.toCollection(ArrayList::new));
System.out.println(arrayList);
HashSet<String> hashSet = Stream.of("aa", "bb", "cc", "aa")
        .collect(Collectors.toCollection(HashSet::new));
System.out.println(hashSet);

5.2 结果收集到数组中

Stream中提供了toArray方法来将结果放到一个数组中,返回值类型是Object[],如果我们要指定返回的 类型,那么可以使用另一个重载的toArray(IntFunction f)方法

// 返回的数组中的元素是 Object类型
Object[] objects = Stream.of("aa", "bb", "cc", "aa")
        .toArray(); 
System.out.println(Arrays.toString(objects));

// 如果我们需要指定返回的数组中的元素类型
String[] strings = Stream.of("aa", "bb", "cc", "aa")
        .toArray(String[]::new);
System.out.println(Arrays.toString(strings));

5.3 对流中的数据做聚合计算

当我们使用Stream流处理数据后,可以像数据库的聚合函数一样对某个字段进行操作,比如获得最大 值,最小值,求和,平均值,统计数量。

// 获取年龄的最大值
Optional<Person> maxAge = Stream.of(
        new Person("张三", 18)
        , new Person("李四", 22)
        , new Person("张三", 13)
        , new Person("王五", 15)
        , new Person("张三", 19)
).collect(Collectors.maxBy((p1, p2) -> p1.getAge() - p2.getAge()));
System.out.println("最大年龄:" + maxAge.get());

// 获取年龄的最小值
Optional<Person> minAge = Stream.of(
        new Person("张三", 18)
        , new Person("李四", 22)
        , new Person("张三", 13)
        , new Person("王五", 15)
        , new Person("张三", 19)
).collect(Collectors.minBy((p1, p2) -> p1.getAge() - p2.getAge()));
System.out.println("最新年龄:" + minAge.get());

// 求所有人的年龄之和
Integer sumAge = Stream.of(
                new Person("张三", 18)
                , new Person("李四", 22)
                , new Person("张三", 13)
                , new Person("王五", 15)
                , new Person("张三", 19)
        )
        .collect(Collectors.summingInt(Person::getAge));
System.out.println("年龄总和:" + sumAge);

// 年龄的平均值
Double avgAge = Stream.of(
        new Person("张三", 18)
        , new Person("李四", 22)
        , new Person("张三", 13)
        , new Person("王五", 15)
        , new Person("张三", 19)
).collect(Collectors.averagingInt(Person::getAge));
System.out.println("年龄的平均值:" + avgAge);

// 统计数量
Long count = Stream.of(
                new Person("张三", 18)
                , new Person("李四", 22)
                , new Person("张三", 13)
                , new Person("王五", 15)
                , new Person("张三", 19)
        ).filter(p -> p.getAge() > 18)
        .collect(Collectors.counting());
System.out.println("满足条件的记录数:" + count);

5.4 对流中数据做分组操作

当我们使用Stream流处理数据后,可以根据某个属性将数据分组

// 根据账号对数据进行分组
Map<String, List<Person>> map1 = Stream.of(
        new Person("张三", 18, 175)
        , new Person("李四", 22, 177)
        , new Person("张三", 14, 165)
        , new Person("李四", 15, 166)
        , new Person("张三", 19, 182)
).collect(Collectors.groupingBy(Person::getName));
map1.forEach((k, v) -> System.out.println("k=" + k + "\t" + "v=" + v));

// 根据年龄分组 如果大于等于18 成年否则未成年
Map<String, List<Person>> map2 = Stream.of(
        new Person("张三", 18, 175)
        , new Person("李四", 22, 177)
        , new Person("张三", 14, 165)
        , new Person("李四", 15, 166)
        , new Person("张三", 19, 182)
).collect(Collectors.groupingBy(p -> p.getAge() >= 18 ? "成年" : "未成年"));
map2.forEach((k, v) -> System.out.println("k=" + k + "\t" + "v=" + v));

多级分组: 先根据name分组然后根据年龄分组

// 先根据name分组,然后根据age(成年和未成年)分组
Map<String, Map<Object, List<Person>>> map = Stream.of(
        new Person("张三", 18, 175)
        , new Person("李四", 22, 177)
        , new Person("张三", 14, 165)
        , new Person("李四", 15, 166)
        , new Person("张三", 19, 182)
).collect(Collectors.groupingBy(
        Person::getName
        , Collectors.groupingBy(p -> p.getAge() >= 18 ? 
        )
));
map.forEach((k, v) -> {
    System.out.println(k);
    v.forEach((k1, v1) -> {
        System.out.println("\t" + k1 + "=" + v1);
    });
});

结果:
李四
	未成年=[org.example.Person@68837a77]
	成年=[org.example.Person@6be46e8f]
张三
	未成年=[org.example.Person@3567135c]
	成年=[org.example.Person@327471b5, org.example.Person@4157f54e]

5.5 对流中的数据做分区操作

Collectors.partitioningBy会根据值是否为true,把集合中的数据分割为两个列表,一个true列表,一个 false列表

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-aumX6KHa-1677243027837)(img\partition.png)]

Map<Boolean, List<Person>> map = Stream.of(
        new Person("张三", 18, 175)
        , new Person("李四", 22, 177)
        , new Person("张三", 14, 165)
        , new Person("李四", 15, 166)
        , new Person("张三", 19, 182)
).collect(Collectors.partitioningBy(p -> p.getAge() > 18));
map.forEach((k, v) -> System.out.println(k + "\t" + v));

5.6 对流中的数据做拼接

Collectors.joining会根据指定的连接符,将所有的元素连接成一个字符串

String s1 = Stream.of(
                new Person("张三", 18, 175)
                , new Person("李四", 22, 177)
                , new Person("张三", 14, 165)
                , new Person("李四", 15, 166)
                , new Person("张三", 19, 182)
        ).map(Person::getName)
        .collect(Collectors.joining());
// 张三李四张三李四张三
System.out.println(s1);
String s2 = Stream.of(
                new Person("张三", 18, 175)
                , new Person("李四", 22, 177)
                , new Person("张三", 14, 165)
                , new Person("李四", 15, 166)
                , new Person("张三", 19, 182)
        ).map(Person::getName)
        .collect(Collectors.joining("_"));
// 张三_李四_张三_李四_张三
System.out.println(s2);
String s3 = Stream.of(
                new Person("张三", 18, 175)
                , new Person("李四", 22, 177)
                , new Person("张三", 14, 165)
                , new Person("李四", 15, 166)
                , new Person("张三", 19, 182)
        ).map(Person::getName)
        .collect(Collectors.joining("_", "###", "$$$"));
// ###张三_李四_张三_李四_张三$$$
System.out.println(s3);

6. 并行的Stream流

我们前面使用的 Stream 流都是串行,也就是在一个线程上面执行。parallelStream 其实就是一个并行执行的流,它通过默认的 ForkJoinPool,可以提高多线程任务的速度。

我们可以通过两种方式来获取并行流。

  1. 通过List接口中的parallelStream方法来获取
  2. 通过已有的串行流转换为并行流(parallel)
List<Integer> list = new ArrayList<>();
// 通过List 接口 直接获取并行流
Stream<Integer> integerStream = list.parallelStream();
// 将已有的串行流转换为并行流
Stream<Integer> parallel = Stream.of(1, 2, 3).parallel();

6.1 并行流操作

Stream.of(1,4,2,6,1,5,9)
        .parallel() // 将流转换为并发流,Stream处理的时候就会通过多线程处理
        .filter(s->{
            System.out.println(Thread.currentThread() + " s=" +s);
            return s > 2;
        }).count();

结果:

Thread[ForkJoinPool.commonPool-worker-5,5,main] s=4
Thread[ForkJoinPool.commonPool-worker-13,5,main] s=2
Thread[ForkJoinPool.commonPool-worker-27,5,main] s=5
Thread[ForkJoinPool.commonPool-worker-9,5,main] s=1
Thread[main,5,main] s=1
Thread[ForkJoinPool.commonPool-worker-19,5,main] s=9
Thread[ForkJoinPool.commonPool-worker-23,5,main] s=6

在结果里面可以看到有6个线程和一个主线程,总共七个线程在处理了

6.2 并行流和串行流对比

我们通过 for 循环,串行 Stream 流,并行 Stream 流来对 5 亿个数字求和。来看消耗时间(每个人电脑不一样,可以有差距,但是,每个方法执行相比的差距是一样的)

public class App {
    private static long times = 500000000; //5亿
    private long start;
    @BeforeEach
    public void before() {
        start = System.currentTimeMillis();
    }
    @AfterEach
    public void end() {
        long end = System.currentTimeMillis();
        System.out.println("消耗时间:" + (end - start));
    }
    /**
     * 普通for循环 消耗时间:322
     */
    @Test
    public void test01() {
        System.out.println("普通for循环:");
        long res = 0;
        for (int i = 0; i < times; i++) {
            res += i;
        }
    }
    /**
     * 串行流处理
     * 消耗时间:291
     */
    @Test
    public void test02() {
        System.out.println("串行流:serialStream");
        LongStream.rangeClosed(0, times)
                .reduce(0, Long::sum);
    }
    /**
     * 并行流处理 消耗时间:84
     */
    @Test
    public void test03() {
        System.out.println("并行流:");
        LongStream.rangeClosed(0, times)
                .parallel()
                .reduce(0, Long::sum);
    }
}

通过案例我们可以看到parallelStream的效率是最高的。 Stream并行处理的过程会分而治之,也就是将一个大的任务切分成了多个小任务,这表示每个任务都是 一个线程操作。

6.3 线程安全问题

在多线程的处理下,肯定会出现数据安全问题。如下:

//单线程
List<Integer> list = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
    list.add(i);
}
System.out.println(list.size());
//多线程
List<Integer> listNew = new ArrayList<>();
// 使用并行流来向集合中添加数据
list.parallelStream().forEach(listNew::add);
System.out.println(listNew.size());

结果:

1000
881

并且有可能会抛出异常:java.lang.ArrayIndexOutOfBoundsException

针对这个问题,我们的解决方案有哪些呢?

  1. 加同步锁
  2. 使用线程安全的容器
  3. 通过Stream中的toArray/collect操作
/**
 * 加同步锁
 */
@Test
public void test02() {
    List<Integer> listNew = new ArrayList<>();
    Object obj = new Object();
    IntStream.rangeClosed(1, 1000)
            .parallel()
            .forEach(i -> {
                synchronized (obj) {
                    listNew.add(i);
                }
            });
    System.out.println(listNew.size());
}

/**
 * 使用线程安全的容器
 */
@Test
public void test03() {
    Vector v = new Vector();
    IntStream.rangeClosed(1, 1000)
            .parallel()
            .forEach(v::add);
    System.out.println(v.size());
}

/**
 * 将线程不安全的容器转换为线程安全的容器
 */
@Test
public void test04() {
    List<Integer> listNew = new ArrayList<>();
    // 将线程不安全的容器包装为线程安全的容器
    List<Integer> synchronizedList = Collections.synchronizedList(listNew);
    IntStream.rangeClosed(1, 1000)
            .parallel()
            .forEach(synchronizedList::add);
    System.out.println(synchronizedList.size());
}

/**
 * 我们还可以通过Stream中的 toArray方法或者 collect方法来操作
 * 就是满足线程安全的要求
 */
@Test
public void test05() {
    List<Integer> list = IntStream.rangeClosed(1, 1000)
            .parallel()
            .boxed()
            .collect(Collectors.toList());
    System.out.println(list.size());
}

rangeClosed 第一个参数接受起始值,第二个参数接受结束值。rangeClosed包含结束值。

有时需要将原始类型转换为包装类型,上述方法实现的是int类型的stream转成了Integer类型的Stream

二. Optional类

这个Optional类注意是解决空指针的问题

1. 以前对 null 的处理

@Test
public void test01(){
    String userName = null;
    if(userName != null){
        System.out.println("字符串的长度:" + userName.length());
    }else{
        System.out.println("字符串为空");
    }
}

Optional 是一个没有子类的工具类,Optional 是一个可以为null的容器对象,它的主要作用就是为了避免 Null 检查,防止 NullpointerException

2. Optional的基本使用

// 第一种方式 通过of方法 
Optional<String> op1 = Optional.of("zhangsan");
Optional<Object> op2 = Optional.of(null); //报错:of方法是不支持null的

// 第二种方式通过 ofNullable方法 支持null
Optional<String> op3 = Optional.ofNullable("lisi");
Optional<Object> op4 = Optional.ofNullable(null);

// 第三种方式 通过empty方法直接创建一个空的Optional对象
Optional<Object> op5 = Optional.empty();

3. Optional的常用方法

  • get():如果Optional有值则返回,否则抛出 NoSuchElementException 异常
  • isPresent():判断是否包含值,包含值返回true,不包含值返回false
  • orElse(T t):如果调用对象包含值,就返回该值,否则返回t
  • orElseGet(Supplier s):如果调用对象包含值,就返回该值,否则返回 Lambda表达式的返回值

示例代码:

Optional<String> op1 = Optional.of("zhangsa
Optional<String> op2 = Optional.empty();
                                   
if (op1.isPresent()) {
    System.out.println(op1.get()); // zhang
}
                                   
if (op2.isPresent()) {
    System.out.println(op2.get());
} else {
    System.out.println("op2是一个空Optional对象")
}
                                   
String s3 = op1.orElse("李四");
System.out.println(s3); // zhangsan
                                   
String s4 = op2.orElse("王五");
System.out.println(s4); // 王五
                                   
String s5 = op2.orElseGet(() -> {
    return "Hello";
});
System.out.println(s5); // Hello

三. 新时间日期API

1. 旧版日期时间的问题

在旧版本中JDK对于日期和时间这块的时间是非常差的。

// 1.设计不合理
Date date = new Date(2021, 05, 05);
System.out.println(date);
// 2.时间格式化和解析操作是线程不安全的
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
for (int i = 0; i < 50; i++) {
    new Thread(() -> {
        // System.out.println(sdf.format(date));
        try {
            System.out.println(sdf.parse("2021-05-06"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }).start();
}
  1. 设计不合理,在java.util和java.sql的包中都有日期类,java.util.Date同时包含日期和时间的,而 java.sql.Date仅仅包含日期,此外用于格式化和解析的类在java.text包下。
  2. 非线程安全,java.util.Date是非线程安全的,所有的日期类都是可变的,这是java日期类最大的问 题之一。
  3. 时区处理麻烦,日期类并不提供国际化,没有时区支持。

2. 新日期时间API

JDK 8中增加了一套全新的日期时间API,这套API设计合理,是线程安全的。新的日期及时间API位于 java.time 包 中,下面是一些关键类。

  • LocalDate :表示日期,包含年月日,格式为 2019-10-16
  • LocalTime :表示时间,包含时分秒,格式为 16:38:54.158549300
  • LocalDateTime :表示日期时间,包含年月日,时分秒,格式为 2018-09-06T15:33:56.750
  • DateTimeFormatter :日期时间格式化类。
  • Instant:时间戳,表示一个特定的时间瞬间。
  • Duration:用于计算2个时间(LocalTime,时分秒)的距离
  • Period:用于计算2个日期(LocalDate,年月日)的距离
  • ZonedDateTime :包含时区的时间

此外Java 8还提供了4套其他历法,分别是:

  • ThaiBuddhistDate:泰国佛教历
  • MinguoDate:中华民国历
  • JapaneseDate:日本历
  • HijrahDate:伊斯兰历

3. 日期时间的常见操作

LocalDate,LocalTime 以及 LocalDateTime 的操作。

基本操作:LocalDate

// 创建指定的日期
LocalDate d = LocalDate.of(2023, 02, 24);
System.out.println("d = "+d); // d = 2023-02-24

// 得到当前的日期
LocalDate now = LocalDate.now();
System.out.println("now = "+now); // now = 2023-02-24

// 根据LocalDate对象获取对应的日期信息
System.out.println("年:" + now.getYear()); // 年:2023
System.out.println("月:" + now.getMonth().getValue()); // 月:2
System.out.println("日:" + now.getDayOfMonth()); // 日:24
System.out.println("星期:" + now.getDayOfWeek().getValue()); // 星期:5

基本操作:LocalTime

// 设置指定的时间
LocalTime time = LocalTime.of(19,46,10,10000);
System.out.println(time); // 19:46:10.000010

// 获取当前的时间
LocalTime now = LocalTime.now();
System.out.println(now); // 19:46:56.288766500

// 获取时间信息
System.out.println(now.getHour()); // 19
System.out.println(now.getMinute()); // 46
System.out.println(now.getSecond()); // 56
System.out.println(now.getNano()); // 288766500

基本操作:LocalDateTime

// 设置指定的日期时间
LocalDateTime dateTime =
        LocalDateTime.of(2023
                , 02
                , 24
                , 19
                , 49
                , 10
                , 10000);
System.out.println(dateTime);

// 获取当前的日期时间
LocalDateTime now = LocalDateTime.now();
System.out.println(now);

// 获取日期时间信息
System.out.println(now.getYear());
System.out.println(now.getMonth().getValue());
System.out.println(now.getDayOfMonth());
System.out.println(now.getDayOfWeek().getValue());
System.out.println(now.getHour());
System.out.println(now.getMinute());
System.out.println(now.getSecond());
System.out.println(now.getNano());

特别方便的是:month – the month-of-year to represent, from 1 (January) to 12 (December),月份从1开始了,就很方便比起以前,以前是0-11的嘛

4. 日期时间的修改和比较

LocalDateTime now = LocalDateTime.now();
System.out.println("now:"+now); // now:2023-02-24T19:55:52.955730100
// 修改日期时间 对日期时间的修改,对已存在的LocalDate对象,创建了它模板
// 并不会修改原来的信息
LocalDateTime localDateTime = now.withYear(1998);
System.out.println("修改后的:" + localDateTime);// 修改后的:1998-02-24T19:55:52.955730100
System.out.println("月份:" + now.withMonth(10));// 月份:2023-10-24T19:55:52.955730100
System.out.println("天:" + now.withDayOfMonth(6));// 天:2023-02-06T19:55:52.955730100
System.out.println("小时:" + now.withHour(8));// 小时:2023-02-24T08:55:52.955730100
System.out.println("分钟:" + now.withMinute(15));// 分钟:2023-02-24T19:15:52.955730100
// 在当前日期时间的基础上 加上或者减去指定的时间
System.out.println("两天后:" + now.plusDays(2));// 两天后:2023-02-26T19:55:52.955730100
System.out.println("10年后:"+now.plusYears(10));// 10年后:2033-02-24T19:55:52.955730100
System.out.println("6个月后 = " + now.plusMonths(6));// 6个月后 = 2023-08-24T19:55:52.955730100
System.out.println("10年前 = " + now.minusYears(10));// 10年前 = 2013-02-24T19:55:52.955730100
System.out.println("半年前 = " + now.minusMonths(6));// 半年前 = 2022-08-24T19:55:52.955730100
System.out.println("一周前 = " + now.minusDays(7));// 一周前 = 2023-02-17T19:55:52.955730100

注意:在进行日期时间修改的时候,原来的LocalDate对象是不会被修改,每次操作都是返回了一个新的 LocalDate对象,所以在多线程场景下是数据安全的。

5. 格式化和解析操作

在JDK8中我们可以通过 java.time.format.DateTimeFormatter 类可以进行日期的解析和格式化操作

LocalDateTime now = LocalDateTime.now();
// 指定格式 使用系统默认的格式
DateTimeFormatter isoLocalDateTime = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
// 将日期时间转换为字符串
String format = now.format(isoLocalDateTime);
System.out.println("format = " + format); // format = 2023-02-24T20:02:59.4295934

// 通过 ofPattern 方法来指定特定的格式
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String format1 = now.format(dateTimeFormatter);
System.out.println("format1 = " + format1); // format1 = 2023-02-24 20:02:59

// 将字符串解析为一个 日期时间类型
LocalDateTime parse = LocalDateTime.parse("2023-05-06 22:45:16", dateTimeFormatter);
System.out.println("parse = " + parse); // parse = 2023-05-06T22:45:16

6. Instant类

在JDK8中给我们新增一个Instant类(时间戳/时间线),内部保存了从1970年1月1日 00:00:00以来的秒和 纳秒

Instant now = Instant.now();
System.out.println("now = " + now);
// 获取从1970年一月一日 00:00:00 到现在的 纳秒
System.out.println(now.getNano());
Thread.sleep(5);//睡眠5毫秒
Instant now1 = Instant.now();
System.out.println("耗时:" + (now1.getNano() - now.getNano()));

7. 计算日期时间差

JDK8中提供了两个工具类Duration/Period:计算日期时间差

  1. Duration:用来计算两个时间差(LocalTime)
  2. Period:用来计算两个日期差(LocalDate)
LocalTime now = LocalTime.now();
LocalTime time = LocalTime.of(20, 00, 0);
System.out.println("now = " + now); // now = 20:12:25.794666100
// 通过Duration来计算时间差
Duration duration = Duration.between(now, time);
System.out.println(duration.toDays()); // 0
System.out.println(duration.toHours()); // 0
System.out.println(duration.toMinutes()); // -12
System.out.println(duration.toSeconds()); // -746
// 计算日期差
LocalDate nowDate = LocalDate.now();
LocalDate date = LocalDate.of(2000, 1, 1);
Period period = Period.between(date, nowDate);
System.out.println(period.getYears()); // 23
System.out.println(period.getMonths()); // 1
System.out.println(period.getDays()); // 23

8. 时间校正器

有时候我们可以需要如下调整:将日期调整到"下个月的第一天"等操作。这时我们通过时间校正器效果 可能会更好。

  • TemporalAdjuster:时间校正器

  • TemporalAdjusters:通过该类静态方法提供了大量的常用TemporalAdjuster的实现。

LocalDateTime now = LocalDateTime.now();
// 将当前的日期调整到下个月的一号
//方式一
TemporalAdjuster adJuster = (temporal) -> {
    LocalDateTime dateTime = (LocalDateTime) temporal;
    LocalDateTime nextMonth = dateTime.plusMonths(1).withDayOfMonth(1);
    System.out.println("nextMonth = " + nextMonth);
    return nextMonth;
};
LocalDateTime nextMonth = now.with(adJuster);

//方式二:我们可以通过TemporalAdjusters 来实现
//LocalDateTime nextMonth = now.with(TemporalAdjusters.firstDayOfNextMonth());
System.out.println("nextMonth = " + nextMonth); // nextMonth = 2023-03-01T20:27:44.397893100

9. 日期时间的时区

Java8 中加入了对时区的支持,LocalDate、LocalTime、LocalDateTime是不带时区的,带时区的日期时间类分别为:ZonedDate、ZonedTime、ZonedDateTime。

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

ZoneId:该类中包含了所有的时区信息

// 获取所有的时区id:ZoneId.getAvailableZoneIds().forEach(System.out::println);
// 获取当前时间 中国使用的 东八区的时区,比标准时间早8个小时
LocalDateTime now = LocalDateTime.now();
System.out.println("now = " + now); // 2023-02-24T20:34:09.990945400

// 获取标准时间
ZonedDateTime bz = ZonedDateTime.now(Clock.systemUTC());
System.out.println("bz = " + bz); // 2023-02-24T12:34:09.994935200Z

// 使用计算机默认的时区,创建日期时间
ZonedDateTime now1 = ZonedDateTime.now();
System.out.println("now1 = " + now1); 
// 2023-02-24T20:34:09.994935200+08:00[Asia/Shanghai]

// 使用指定的时区创建日期时间
ZonedDateTime now2 = ZonedDateTime.now(ZoneId.of("America/Marigot"));
System.out.println("now2 = " + now2); 
// 2023-02-24T08:34:09.995931900-04:00[America/Marigot]

四. 其他新特性

1. 重复注解

自从Java 5中引入 注解 以来,注解开始变得非常流行,并在各个框架和项目中被广泛使用。不过注 解有一个很大的限 制是:在同一个地方不能多次使用同一个注解。JDK 8引入了重复注解的概念,允许在同一个地方多次使用同一个注解。

在JDK 8中使用@Repeatable注解定义重复注解。

定义一个重复注解的容器

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotations {
	MyAnnotation[] value();
}

定义一个可以重复的注解

@Repeatable(MyAnnotations.class)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
	String value();
}

配置多个重复的注解

@MyAnnotation("test1")
@MyAnnotation("test2")
@MyAnnotation("test3")
public class AnnoTest01 {
    
    @MyAnnotation("fun1")
    @MyAnnotation("fun2")
    public void test01(){
        
    }
}

解析得到指定的注解

// 获取类中标注的重复注解
MyAnnotation[] annotationsByType = AnnoTest01.class.getAnnotationsByType(MyAnnotation.class);
for (MyAnnotation myAnnotation : annotationsByType) {
    System.out.println(myAnnotation.value());
}
// 获取方法上标注的重复注解
MyAnnotation[] test01s = AnnoTest01.class.getMethod("test01")
        .getAnnotationsByType(MyAnnotation.class);
for (MyAnnotation test01 : test01s) {
    System.out.println(test01.value());
}

2. 类型注解

JDK 8 为 @Target 元注解新增了两种类型: TYPE_PARAMETER , TYPE_USE

  • TYPE_PARAMETER :表示该注解能写在类型参数的声明语句中。

  • TYPE_USE :表示注解可以再任何用到类型的地方使用。

TYPE_PARAMETER 案例:

@Target(ElementType.TYPE_PARAMETER)
public @interface TypeParam {
    
}
public class TypeDemo01 <@TypeParam T> {
    public <@TypeParam K extends Object> K test01(){
    	return null;
    }
}

TYPE_USE 案例:

@Target(ElementType.TYPE_USE)
public @interface NotNull {
}
public class TypeUseDemo01 {
    
	public @NotNull Integer age = 10;
    
    public Integer sum(@NotNull Integer a,@NotNull Integer b){
    	return a + b;
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

北京李嘉城

我的好兄弟啊,感谢大佬的火箭!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值