在java的optional中,lambda表达式通过map()方法实现链式转换,将optional中的值映射为optional。具体做法是调用optional.map(value -> value * 2),如果optional包含值则执行lambda并包装结果,若为空则保持空状态且不触发lambda。

如何安全地提取嵌套对象属性
使用flatMap()处理返回Optional的方法,避免产生Optional的双重包裹。例如从用户对象中提取地址时,直接链接map(User::getAddress).flatMap(Address::getCity)即可。

import java.util.Optional;
public class User {
private String name;
private Address address;
public static Optional<user> findUser(String id) {
return Optional.of(new User("Alice", new Address("Beijing")));
}
public Address getAddress() { return address; }
public User(String name, Address address) { this.name = name; this.address = address; }
}
class Address {
private String city;
public Optional<string> getCity() { return Optional.ofNullable(city); }
public Address(String city) { this.city = city; }
}
public class Main {
public static void main(String[] args) {
Optional<user> userOpt = User.findUser("123");
String city = userOpt
.map(u -> u.getAddress())
.flatMap(a -> a.getCity())
.orElse("Unknown");
System.out.println(city);
}
}</user></string></user>
如何处理转换过程中的异常或空值
在Lambda内部结合filter()进行条件过滤,或使用orElseThrow()抛出特定异常。当输入可能为null或不符合业务逻辑时,filter()会将Optional变为空,从而跳过后续操作。

import java.util.Optional;
public class Main {
public static void main(String[] args) {
Optional<integer> opt = Optional.of(5);
// 使用 filter 排除负数
int result = opt
.filter(n -> n > 0)
.map(n -> n * 10)
.orElse(-1);
System.out.println(result); // 输出 50
// 使用 orElseThrow 处理缺失值
try {
int val = Optional.empty()
.map(n -> n * 10)
.orElseThrow(() -> new RuntimeException("Value missing"));
} catch (RuntimeException e) {
System.out.println(e.getMessage());
}
}
}</integer>
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











