Java8 中的真的 Optional 很强大,你用对了吗?
逆锋起笔
共 9798字,需浏览 20分钟
·
2021-11-15 19:28
来源:oschina.net/dzone.com/articles/understanding-accepting-and-leveraging-optional-in
String isocode = user.getAddress().getCountry().getIsocode().toUpperCase();
if (user != null) {
Address address = user.getAddress();
if (address != null) {
Country country = address.getCountry();
if (country != null) {
String isocode = country.getIsocode();
if (isocode != null) {
isocode = isocode.toUpperCase();
}
}
}
}
创建 Optional 实例
@Test(expected = NoSuchElementException.class)
public void whenCreateEmptyOptional_thenNull() {
OptionalemptyOpt = Optional.empty();
emptyOpt.get();
}
@Test(expected = NullPointerException.class)
public void whenCreateOfEmptyOptional_thenNullPointerException() {
Optionalopt = Optional.of(user);
}
Optional opt = Optional.ofNullable(user);
访问 Optional 对象的值
@Test
public void whenCreateOfNullableOptional_thenOk() {
String name = "John";
Optionalopt = Optional.ofNullable(name);
assertEquals("John", opt.get());
}
@Test
public void whenCheckIfPresent_thenOk() {
User user = new User("john@gmail.com", "1234");
Optionalopt = Optional.ofNullable(user);
assertTrue(opt.isPresent());
assertEquals(user.getEmail(), opt.get().getEmail());
}
opt.ifPresent( u -> assertEquals(user.getEmail(), u.getEmail()));
返回默认值
@Test
public void whenEmptyValue_thenReturnDefault() {
User user = null;
User user2 = new User("anna@gmail.com", "1234");
User result = Optional.ofNullable(user).orElse(user2);
assertEquals(user2.getEmail(), result.getEmail());
}
@Test
public void whenValueNotNull_thenIgnoreDefault() {
User user = new User("john@gmail.com","1234");
User user2 = new User("anna@gmail.com", "1234");
User result = Optional.ofNullable(user).orElse(user2);
assertEquals("john@gmail.com", result.getEmail());
}
User result = Optional.ofNullable(user).orElseGet( () -> user2);
orElse() 和 orElseGet() 的不同之处
@Test
public void givenEmptyValue_whenCompare_thenOk() {
User user = null
logger.debug("Using orElse");
User result = Optional.ofNullable(user).orElse(createNewUser());
logger.debug("Using orElseGet");
User result2 = Optional.ofNullable(user).orElseGet(() -> createNewUser());
}
private User createNewUser() {
logger.debug("Creating New User");
return new User("extra@gmail.com", "1234");
}
Using orElse
Creating New User
Using orElseGet
Creating New User
@Testpublic void givenPresentValue_whenCompare_thenOk() { User user = new User("john@gmail.com", "1234"); logger.info("Using orElse"); User result = Optional.ofNullable(user).orElse(createNewUser()); logger.info("Using orElseGet"); User result2 = Optional.ofNullable(user).orElseGet(() -> createNewUser());}
Using orElseCreating New UserUsing orElseGet
返回异常
@Test
public void givenPresentValue_whenCompare_thenOk() {
User user = new User("john@gmail.com", "1234");
logger.info("Using orElse");
User result = Optional.ofNullable(user).orElse(createNewUser());
logger.info("Using orElseGet");
User result2 = Optional.ofNullable(user).orElseGet(() -> createNewUser());
}
转换值
@Test
public void whenMap_thenOk() {
User user = new User("anna@gmail.com", "1234");
String email = Optional.ofNullable(user)
.map(u -> u.getEmail()).orElse("default@gmail.com");
assertEquals(email, user.getEmail());
}
public class User {
private String position;
public OptionalgetPosition() {
return Optional.ofNullable(position);
}
//...
}
@Test
public void whenFlatMap_thenOk() {
User user = new User("anna@gmail.com", "1234");
user.setPosition("Developer");
String position = Optional.ofNullable(user)
.flatMap(u -> u.getPosition()).orElse("default");
assertEquals(position, user.getPosition().get());
}
过滤值
@Test
public void whenFilter_thenOk() {
User user = new User("anna@gmail.com", "1234");
Optionalresult = Optional.ofNullable(user)
.filter(u -> u.getEmail() != null && u.getEmail().contains("@"));
assertTrue(result.isPresent());
}
Optional 类的链式方法
public class User {
private Address address;
public Optional getAddress() {
return Optional.ofNullable(address);
}
// ...
}
public class Address {
private Country country;
public OptionalgetCountry() {
return Optional.ofNullable(country);
}
// ...
}
@Test
public void whenChaining_thenOk() {
User user = new User("anna@gmail.com", "1234");
String result = Optional.ofNullable(user)
.flatMap(u -> u.getAddress())
.flatMap(a -> a.getCountry())
.map(c -> c.getIsocode())
.orElse("default");
assertEquals(result, "default");
}
String result = Optional.ofNullable(user)
.flatMap(User::getAddress)
.flatMap(Address::getCountry)
.map(Country::getIsocode)
.orElse("default");
Java 9 增强
@Test
public void whenEmptyOptional_thenGetValueFromOr() {
User result = Optional.ofNullable(user)
.or( () -> Optional.of(new User("default","1234"))).get();
assertEquals(result.getEmail(), "default");
}
Optional.ofNullable(user).ifPresentOrElse( u -> logger.info("User is:" + u.getEmail()),
() -> logger.info("User not found"));
@Test
public void whenGetStream_thenOk() {
User user = new User("john@gmail.com", "1234");
Listemails = Optional.ofNullable(user)
.stream()
.filter(u -> u.getEmail() != null && u.getEmail().contains("@"))
.map( u -> u.getEmail())
.collect(Collectors.toList());
assertTrue(emails.size() == 1);
assertEquals(emails.get(0), user.getEmail());
}
Optional 应该怎样用?
User user = new User("john@gmail.com", "1234", Optional.empty());
@Test
public void whenEmptyStream_thenReturnDefaultOptional() {
Listusers = new ArrayList<>();
User user = users.stream().findFirst().orElse(new User("default", "1234"));
assertEquals(user.getEmail(), "default");
}
总结
逆锋起笔
是一个专注于程序员圈子的技术平台,你可以收获最新技术动态
、最新内测资格
、BAT等大厂的经验
、精品学习资料
、职业路线
、副业思维
,微信搜索逆锋起笔
关注!
评论