暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Optiaonal学习​

随遇而安jml 2020-09-13
102

1、Optional.empty()  返回optional的null的值 ,没啥作用

2、ptional.of(value) 如果值为空则报错

3、filter(Predicate predicate)

OptionalofNullable = Optional.ofNullable(user);

       Optionalfilter = ofNullable.filter(new Predicate(){

              @Override

              public boolean test(User user) {

                     return "jml".equals(user.getUserName()) ? true :false;

              }});

4、equals还不如直接使用Object

       boolean equals = ofNullable.equals(user2);

       System.out.println(equals);

       Objects.equals(value, other.value)

5、flatMap

       String string = ofNullable.map(t->t.getAge()).get();



6、ofNullable  1与2的结合常用

7、Objects类好东西

int compare = Objects.compare(user, user2, new Comparator(){

              @Override

              public int compare(User o1, User o2) {

                     if (o1 == o2 || (o1 != null && o2 != null && o1.getAge() == o2.getAge()))

                     {

                            return 0;

                     }

                     return -1;

              }      

       });


8、orElse返回值如果存在否则返回 other 。

       String string = ofNullable.map(t->t.getAge()).orElse("67");


9、orElseGet返回值(如果存在),否则调用 other并返回该调用的结果。

String string = ofNullable.map(t->t.getAge()).orElseGet(()->{return "5";});

10、publicT orElseThrow(Supplier exceptionSupplier)throws X extends Throwable返回包含的值(如果存在),否则抛出由提供的供应商创建的异常。

ofNullable.map(t->t.getAge()).orElseThrow(()->new Exception());

Eg:

       myException myException = new TextUtil().new myException("");

       ofNullable.map(t->t.getAge()).orElseThrow(()->myException);

 class myException extends Exception{

       /**

       * @Description:

       * @date: 2020年9月13日 下午2:53:06

       */

       private static final long serialVersionUID = 1L;

       private String message;

       public myException(String message)

       {

              this.message = message;

       }

       @Override

       public String getMessage() {

              return this.message;

       }

 }




注意:Objects类有比较多的工具类

文章转载自随遇而安jml,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论