LoginSignup
0
1

More than 5 years have passed since last update.

Java8のお勉強(Optional)

Posted at

Optionalのお勉強です
サンプル

/**
 * オプショナルのお勉強
 * @author komikcomik
 *
 */
public class OptionalHello {
    public static void main(String[] args) {
        String nullです = null;
        String nullじゃないよ = "abc";

        if (Optional.ofNullable(nullです).equals(Optional.empty())) {
            System.out.println("nullでした");
        } else {
            System.out.println("nullじゃなかったよ");
        }

        if (Optional.ofNullable(nullじゃないよ).equals(Optional.empty())) {
            System.out.println("nullでした2");
        } else {
            System.out.println("nullじゃなかったよ2");
        }

        Optional.ofNullable(nullです).ifPresent(s -> System.out.println(s));
        Optional.ofNullable(nullじゃないよ).ifPresent(s -> System.out.println(s));
    }

}

実行結果

nullでした
nullじゃなかったよ2
abc

今回例がイケてないですが実際にはメソッドの戻り値にOptionalを使うといいみたいですね。

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