From 29aad55a478c49d7062945043f90f5b2a424ed50 Mon Sep 17 00:00:00 2001 From: zeekling Date: Sun, 20 Jun 2021 16:55:19 +0800 Subject: [PATCH] Optional --- .../com/zeekling/optional/Java8Tester.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/main/java/com/zeekling/optional/Java8Tester.java diff --git a/src/main/java/com/zeekling/optional/Java8Tester.java b/src/main/java/com/zeekling/optional/Java8Tester.java new file mode 100644 index 0000000..fe81d1c --- /dev/null +++ b/src/main/java/com/zeekling/optional/Java8Tester.java @@ -0,0 +1,42 @@ +package com.zeekling.optional; + +import java.util.Optional; + +/** + * @author zeekling + * @apiNote Optional 实例 + * @since 2021-06-20 + */ +public class Java8Tester { + + + public static void main(String args[]){ + + Java8Tester java8Tester = new Java8Tester(); + Integer value1 = null; + Integer value2 = new Integer(10); + + // Optional.ofNullable - 允许传递为 null 参数 + Optional a = Optional.ofNullable(value1); + + // Optional.of - 如果传递的参数是 null,抛出异常 NullPointerException + Optional b = Optional.of(value2); + System.out.println(java8Tester.sum(a,b)); + } + + public Integer sum(Optional a, Optional b){ + + // Optional.isPresent - 判断值是否存在 + + System.out.println("第一个参数值存在: " + a.isPresent()); + System.out.println("第二个参数值存在: " + b.isPresent()); + + // Optional.orElse - 如果值存在,返回它,否则返回默认值 + Integer value1 = a.orElse(new Integer(0)); + + //Optional.get - 获取值,值需要存在 + Integer value2 = b.get(); + return value1 + value2; + } + +}