参考下述网址的内容写了一个optional的demo
https://blog.csdn.net/yangxiao_hui/article/details/89853413
import java.util.Optional;
class Scratch {
public static void main(String[] args) throws Exception {
User user = new User();
user.setName("zhangsan1");
Address address = new Address();
address.setCity("city");
user.setAddress(address);
//orElseThrow
//test1Old(user);
test1New(user);
//ifPresent
test2Old(user);
test2New(user);
//orElseGet
System.out.println(test3Old(user).toString());
System.out.println(test3New(user).toString());
//flatMap map
//flatMap不会用funcation的结果进行包装,map会包装成Optional
//所以如果本来就是Optional<String>的属性,直接flatMap就可以了
}
public static void test1Old(User user) throws Exception {
if (user != null) {
if (user.getAddress() != null) {
Address address = user.getAddress();
if (address.getCity() != null) {
System.out.println(address.getCity());
}
}
} else {
throw new Exception("取值错误");
}
}
public static void test1New(User user) throws Exception {
System.out.println(Optional.ofNullable(user)
.map(u -> u.getAddress())
.map(a -> a.getCity())
.orElseThrow(() -> new Exception("取值错误")));
}
public static void test2Old(User user) {
if (user != null) {
System.out.println(user.toString());
}
}
public static void test2New(User user) {
Optional.ofNullable(user).ifPresent(u -> {
System.out.println(u.toString());
});
}
public static User test3Old(User user) {
if (user != null) {
String name = user.getName();
if ("zhangsan".equals(name)) {
return user;
} else {
user = new User();
user.setName("LiSi");
}
}
return user;
}
public static User test3New(User user) {
return Optional.ofNullable(user)
.filter(u -> "zhangsan".equals(u.getName()))
.orElseGet(() -> {
user.setName("LiSi");
return user;
});
}
static class User {
private String name;
private Address address;
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", address=" + address +
'}';
}
public void setAddress(Address address) {
this.address = address;
}
public Address getAddress() {
return address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
static class Address {
private String city;
public void setCity(String city) {
this.city = city;
}
public String getCity() {
return city;
}
}
}
参考文章
- https://blog.csdn.net/yangxiao_hui/article/details/89853413