答应我,别再靠!= null走天下了可以吗?
这里是码农充电第一站,回复“666”,获取一份专属大礼包 真爱,请设置“星标”或点个“在看”
常规判断://对象 人//属性有 name,agePerson person=new Person();if (null==person){return "person为null";}return person;
使用Optional://对象 人//属性有 name,agePerson person=new Person();return Optional.ofNullable(person).orElse("person为null");
public class Person {private String name;private Integer age;public Person(String name, Integer age) {this.name = name;this.age = age;}public Person() {}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}}
public final class Optional{ private static final Optional> EMPTY = new Optional<>();private final T value;//我们可以看到两个构造方格都是private 私有的//说明 我们没办法在外面去new出来Optional对象private Optional() {this.value = null;}private Optional(T value) {this.value = Objects.requireNonNull(value);}//这个静态方法大致 是创建出一个包装值为空的一个对象因为没有任何参数赋值public staticOptional empty() { @SuppressWarnings("unchecked")Optionalt = (Optional ) EMPTY; return t;}//这个静态方法大致 是创建出一个包装值非空的一个对象 因为做了赋值public staticOptional of(T value) { return new Optional<>(value);}//这个静态方法大致是 如果参数value为空,则创建空对象,如果不为空,则创建有参对象public staticOptional ofNullable(T value) { return value == null ? empty() : of(value);}}
// 1、创建一个包装对象值为空的Optional对象OptionaloptEmpty = Optional.empty(); // 2、创建包装对象值非空的Optional对象OptionaloptOf = Optional.of("optional"); // 3、创建包装对象值允许为空也可以不为空的Optional对象OptionaloptOfNullable1 = Optional.ofNullable(null); OptionaloptOfNullable2 = Optional.ofNullable("optional");
public T get() {if (value == null) {throw new NoSuchElementException("No value present");}return value;}
Person person=new Person();person.setAge(2);Optional.ofNullable(person).get();
public boolean isPresent() {return value != null;}
Person person=new Person();person.setAge(2);if (Optional.ofNullable(person).isPresent()){//写不为空的逻辑System.out.println("不为空");}else{//写为空的逻辑System.out.println("为空");}
public void ifPresent(Consumer super T> consumer) {//如果value不为空,则运行accept方法体if (value != null)consumer.accept(value);}
Person person=new Person();person.setAge(2);Optional.ofNullable(person).ifPresent(p -> System.out.println("年龄"+p.getAge()));
public Optionalfilter(Predicate super T> predicate) { Objects.requireNonNull(predicate);//如果为空直接返回thisif (!isPresent())return this;else//判断返回本身还是空Optionalreturn predicate.test(value) ? this : empty();}
Person person=new Person();person.setAge(2);Optional.ofNullable(person).filter(p -> p.getAge()>50);
public Optional map(Function super T, ? extends U> mapper) {Objects.requireNonNull(mapper);//如果为空返回自己if (!isPresent())return empty();else {//否则返回用方法修饰过的Optionalreturn Optional.ofNullable(mapper.apply(value));}}
Person person1=new Person();person.setAge(2);String optName = Optional.ofNullable(person).map(p -> person.getName()).orElse("name为空");
public Optional flatMap(Function super T, Optional> mapper) {Objects.requireNonNull(mapper);if (!isPresent())return empty();else {return Objects.requireNonNull(mapper.apply(value));}}
Person person=new Person();person.setAge(2);Optional
public T orElse(T other) {//如果非空,返回value,如果为空,返回otherreturn value != null ? value : other;}
Person person1=new Person();person.setAge(2);Optional.ofNullable(person).orElse(new Person("小明", 2));
public T orElseGet(Supplier extends T> other) {return value != null ? value : other.get();}
Optional> sup=Optional.ofNullable(Person::new); //调用get()方法,此时才会调用对象的构造方法,即获得到真正对象Optional.ofNullable(person).orElseGet(sup.get());
publicT orElseThrow(Supplier extends X> exceptionSupplier) throws X { if (value != null) {return value;} else {throw exceptionSupplier.get();}}
//简单的一个查询Member member = memberService.selectByPhone(request.getPhone());Optional.ofNullable(member).orElseThrow(() -> new ServiceException("没有查询的相关数据"));
//查询一个对象Member member = memberService.selectByIdNo(request.getCertificateNo());//使用ofNullable加orElseThrow做判断和操作Optional.ofNullable(member).orElseThrow(() -> new ServiceException("没有查询的相关数据"));
public interface LocationRepository extends JpaRepository{ OptionalfindLocationById(String id); }
public TerminalVO findById(String id) {//这个方法在dao层也是用了Optional包装了OptionalterminalOptional = terminalRepository.findById(id); //直接使用isPresent()判断是否为空if (terminalOptional.isPresent()) {//使用get()方法获取对象值Terminal terminal = terminalOptional.get();//在实战中,我们已经免去了用set去赋值的繁琐,直接用BeanCopy去赋值TerminalVO terminalVO = BeanCopyUtils.copyBean(terminal, TerminalVO.class);//调用dao层方法返回包装后的对象Optionallocation = locationRepository.findLocationById(terminal.getLocationId()); if (location.isPresent()) {terminalVO.setFullName(location.get().getFullName());}return terminalVO;}//不要忘记抛出异常throw new ServiceException("该终端不存在");}
Person person=new Person();person.setName("");persion.setAge(2);//普通判断if(StringUtils.isNotBlank(person.getName())){//名称不为空执行代码块}//使用Optional做判断Optional.ofNullable(person).map(p -> p.getName()).orElse("name为空");
(完)
码农突围资料链接
1、卧槽!字节跳动《算法中文手册》火了,完整版 PDF 开放下载!
2、计算机基础知识总结与操作系统 PDF 下载
3、艾玛,终于来了!《LeetCode Java版题解》.PDF
4、Github 10K+,《LeetCode刷题C/C++版答案》出炉.PDF欢迎添加鱼哥个人微信:smartfish2020,进粉丝群或围观朋友圈。
评论

