LoginSignup
2
2

More than 5 years have passed since last update.

Java8 Optional の使いどころ(自分用)

Posted at

自分にとってのOptionalの価値は下記と思われる

String result = "";     //初期化
AaaaModel aaaaRec = aaaaMapper.find("the_id");
if(aaaaModel != null){  //null チェック
    String title = aaaaRec.getTitle();
    if(title != null){  //null チェック
        BbbbModel bbbbRec = bbbbMapper.find(title);
        if(bbbbRec  != null){  //null チェック
            String theId = bbbbRe.getId();
            if(theId != null){  //null チェック
                result = theId ;
            }
        }
    }
}

java8で書く
String result = Optional.ofNullable(aaaaMapper.find("the_id"))
    .map(aaaaRec -> aaaaRec.getTitle())
    .map(title -> bbbbMapper.find(title))
    .map(bbbbRec -> bbbbRec.getId())
    .orElse("");
2
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2