Optional 是个好东西,你真的会用么?
码农突围
共 12108字,需浏览 25分钟
·
2021-05-10 19:11
点击上方“码农突围”,马上关注 这里是码农充电第一站,回复“666”,获取一份专属大礼包 真爱,请设置“星标”或点个“在看”
引言
user.getAddress().getProvince();
if(user!=null){
Address address = user.getAddress();
if(address!=null){
String province = address.getProvince();
}
}
API介绍
Optional(T value),empty(),of(T value),ofNullable(T value)
public static <T> Optional<T> of(T value) {
return new Optional<>(value);
}
通过of(T value)函数所构造出的Optional对象,当Value值为空时,依然会报NullPointerException。 通过of(T value)函数所构造出的Optional对象,当Value值不为空时,能正常构造Optional对象。
public final class Optional<T> {
//省略....
private static final Optional<?> EMPTY = new Optional<>();
private Optional() {
this.value = null;
}
//省略...
public static<T> Optional<T> empty() {
@SuppressWarnings("unchecked")
Optional<T> t = (Optional<T>) EMPTY;
return t;
}
}
public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}
orElse(T other),orElseGet(Supplier<? extends T> other)和orElseThrow(Supplier<? extends X> exceptionSupplier)
@Test
public void test() {
User user = null;
user = Optional.ofNullable(user).orElse(createUser());
user = Optional.ofNullable(user).orElseGet(() -> createUser());
}
public User createUser(){
User user = new User();
user.setName("zhangsan");
return user;
}
User user = null;
Optional.ofNullable(user).orElseThrow(()->new Exception("用户不存在"));
map(Function<? super T, ? extends U> mapper)和flatMap(Function<? super T, Optional<U>> mapper)
public final class Optional<T> {
//省略....
public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent())
return empty();
else {
return Optional.ofNullable(mapper.apply(value));
}
}
//省略...
public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent())
return empty();
else {
return Objects.requireNonNull(mapper.apply(value));
}
}
}
Function<? super T, ? extends U>
,而flapMap的入参类型为Function<? super T, Optional<U>>
。public class User {
private String name;
public String getName() {
return name;
}
}
String city = Optional.ofNullable(user).map(u-> u.getName()).get();
public class User {
private String name;
public Optional<String> getName() {
return Optional.ofNullable(name);
}
}
String city = Optional.ofNullable(user).flatMap(u-> u.getName()).get();
isPresent()
和ifPresent(Consumer<? super T> consumer)
public final class Optional<T> {
//省略....
public boolean isPresent() {
return value != null;
}
//省略...
public void ifPresent(Consumer<? super T> consumer) {
if (value != null)
consumer.accept(value);
}
}
if (user != null){
// TODO: do something
}
User user = Optional.ofNullable(user);
if (Optional.isPresent()){
// TODO: do something
}
ifPresent(Consumer<? super T> consumer)
,用法也很简单,如下所示Optional.ofNullable(user).ifPresent(u->{
// TODO: do something
});
filter(Predicate<? super T> predicate)
public final class Optional<T> {
//省略....
Objects.requireNonNull(predicate);
if (!isPresent())
return this;
else
return predicate.test(value) ? this : empty();
}
Optional<User> user1 = Optional.ofNullable(user).filter(u -> u.getName().length()<6);
实战使用
public String getCity(User user) throws Exception{
if(user!=null){
if(user.getAddress()!=null){
Address address = user.getAddress();
if(address.getCity()!=null){
return address.getCity();
}
}
}
throw new Excpetion("取值错误");
}
public String getCity(User user) throws Exception{
return Optional.ofNullable(user)
.map(u-> u.getAddress())
.map(a->a.getCity())
.orElseThrow(()->new Exception("取指错误"));
}
if(user!=null){
dosomething(user);
}
Optional.ofNullable(user)
.ifPresent(u->{
dosomething(u);
});
public User getUser(User user) throws Exception{
if(user!=null){
String name = user.getName();
if("zhangsan".equals(name)){
return user;
}
}else{
user = new User();
user.setName("zhangsan");
return user;
}
}
public User getUser(User user) {
return Optional.ofNullable(user)
.filter(u->"zhangsan".equals(u.getName()))
.orElseGet(()-> {
User user1 = new User();
user1.setName("zhangsan");
return user1;
});
}
- END - 最近热文
• 尼玛,Github上最邪恶的开源项目了!未满18或者女孩子勿进哦~ • 永别了,91网站!宣布永久关闭 • 腾讯员工晒出薪资:真实 985 毕业薪资,大家看我还有救吗?网友:日薪? • 再见深圳!我要去成都搞IT了!
评论