LoginSignup
1
1

More than 5 years have passed since last update.

Java8のOptionalでSomeの時とEmptyの時の処理

Posted at

Optionalを使ってて、SomeのときとEmptyのときで処理を変えたい場合

Optional<Hoge> hoge = repository.find("hoge");
if (hoge.isPresent()) {
    // some processing.
    return ok(hogeJson);
} 

return badRequest("sorry...");

FPっぽくかけないかなーと思ったので以下の感じにした。

return repository.find("hoge")
  .map(hoge -> {
    // some processing.
    return ok(hogeJson);
  })
  .orElse(badRequest("sorry..."));

すっきりした。

こんな書き方もできるんだ…


return repository.find("hoge")
  .<Supplier>map(hoge -> () -> {
      // some processing
      return Ok(hogeJson);
  })
  .orElse(() -> {
      return NotFound("sorry...");
  })
  .get()

なんか、これだとあんまり意味ないか。
高階関数の使い道がいまいちまだわからない…

1
1
0

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
1
1