代码改变世界

java optional

2022-03-05 20:33  tonyniu8  阅读(15)  评论(0编辑  收藏  举报

#1. 创建实例

 private static void createOptional(){
        //1. create instance
        // use of or ofNullable
        //of need to ensure it is not empty
        Person nullPerson=null;
        String nullName=getNameWithOptional(nullPerson);
        System.out.println(nullName);

        Person person = new Person("junjun", 18);
        Person  result = Optional.ofNullable(nullPerson).orElse(person);
        System.out.println("the default method");
        System.out.println(result);
    }

#2.访问optional对象值

    // T get() // if it is null: NoSuchElementException.
    // isPresent,whether value exist.
    // void ifPresent(Consumer<?super T> consume)
    // 2.get ,if it is null: noSuchElementException
    private static String getValue(Person person) {
        Optional<Person> personOptional= Optional.ofNullable(person);
        if(personOptional.isPresent()){
            Optional.ofNullable(person).get();
        }
        return personOptional.get().getName();
    }

#3.返回默认值

    // 3.orElse , return default value
    private static String getOrElse() {
        Person person = null;
        Person defaultPerson =new Person("zhangsan",20);
        Person p= Optional.ofNullable(person).orElse(defaultPerson);
        //orElseGet, when value is null , it will call method
        Person p2= Optional.ofNullable(person).orElseGet(()->createPerson());
        return p.getName();

    }

#4.返回异常

    //4. orElseThrow
    // throw user defined exception, when object is null
    private static String orElseThrow(Person person) {
        Person p= Optional.ofNullable(person).orElseThrow(()->new IllegalArgumentException());
        return p.getName();
    }

#5. 值转换

    //5. value mapping

    private static String valueMapping(Person person) {
        String name = Optional.ofNullable(person).map(x -> x.getName())
                .orElse("unKnown");
        return name;
    }

# ref:

  1. https://www.cnblogs.com/zhangboyu/p/7580262.html