好的,我们来系统讲解 Java 中的 Optional,帮助你理解它的作用、学习用法,并附上实践示例。
Optional<T> 是 Java 8 引入的一个容器类,用来 防止 NullPointerException (NPE),表示 一个值可能存在,也可能不存在。
import java.util.Optional;
public class OptionalDemo {
public static void main(String[] args) {
// 1. of(T value):创建一个非 null Optional
Optional<String> opt1 = Optional.of("Hello");
// 2. ofNullable(T value):允许 null 值
Optional<String> opt2 = Optional.ofNullable(null);
// 3. empty():创建一个空 Optional
Optional<String> opt3 = Optional.empty();
}
}方法 | 说明 |
|---|---|
isPresent() | 判断值是否存在 |
ifPresent(Consumer<? super T> action) | 如果值存在,执行 action |
orElse(T other) | 值存在则返回,否则返回 other |
orElseGet(Supplier<? extends T> other) | 值存在则返回,否则执行 Supplier 获取值 |
orElseThrow(Supplier<? extends Throwable> exceptionSupplier) | 值存在则返回,否则抛异常 |
map(Function<? super T,? extends U> mapper) | 对值执行函数映射,并返回 Optional |
flatMap(Function<? super T, Optional<U>> mapper) | 对值执行函数映射,返回 Optional(避免嵌套 Optional) |
filter(Predicate<? super T> predicate) | 值存在且满足条件返回 Optional,否则返回 empty |
Optional<String> name = Optional.ofNullable(getUserName());
String result = name.orElse("Default Name");
System.out.println(result);如果 getUserName() 返回 null,orElse 会提供默认值。
Optional<String> email = Optional.ofNullable(getUserEmail());
email.ifPresent(e -> System.out.println("Email: " + e));只有在 email 存在时才会打印。
Optional<User> userOpt = Optional.ofNullable(getUser());
String email = userOpt
.map(User::getProfile) // map 返回 Optional<Profile>
.map(Profile::getEmail) // map 返回 Optional<String>
.orElse("no-email@example.com");
System.out.println(email);map 可以连续操作,处理可能为 null 的链式调用。
if (user != null && user.getProfile() != null) {
email = user.getProfile().getEmail();
} else {
email = "no-email@example.com";
}Optional<String> phoneOpt = Optional.ofNullable(user.getPhone());
phoneOpt.filter(p -> p.startsWith("+86"))
.ifPresent(p -> System.out.println("Chinese number: " + p));filter 对值做条件筛选,不满足条件会返回 empty。
Optional<User> userOpt = Optional.ofNullable(getUser());
User user = userOpt.orElseThrow(() -> new RuntimeException("User not found"));List<Optional<T>> 不推荐。集合本身可以为空或空集合表示不存在。
map + flatMap 避免嵌套 null 判断。
ifPresent、orElseGet、filter 都能让代码更简洁。
import java.util.Optional;
class Profile {
private String email;
public Profile(String email) { this.email = email; }
public String getEmail() { return email; }
}
class User {
private Profile profile;
public User(Profile profile) { this.profile = profile; }
public Profile getProfile() { return profile; }
}
public class OptionalExample {
public static void main(String[] args) {
User user = new User(null);
// 使用 Optional 链式调用获取邮箱
String email = Optional.ofNullable(user)
.map(User::getProfile)
.map(Profile::getEmail)
.orElse("no-email@example.com");
System.out.println(email); // 输出 no-email@example.com
}
}总结:
Optional 是 Java 8 防止 NPE 的工具。
orElse, orElseGet, orElseThrow 等方法处理缺省值。
map, flatMap, filter),简化嵌套对象处理。
https://www.52runoob.com/archives/7547
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。