LoginSignup
1
0

More than 3 years have passed since last update.

[Java] IntStreamでorElseとorElseGetの違いを確認

Last updated at Posted at 2019-06-28

osElse

OptionalIntがnullのとき、引数のint値を返す

System.out.println(IntStream.of(1, 2, 3).findFirst().orElse(100)); //=> findFirstで獲得した1を返す

System.out.println(IntStream.of().findFirst().orElse(100)); //=>findFirstで獲得できないため、引数の100を返す

orElseGet

OptionalIntがnullのとき、引数のSupplierを実行

System.out.println(IntStream.of(1, 2, 3).findFirst().orElseGet(() -> 100)); //=> findFirstで獲得した1を返す

System.out.println(IntStream.of().findFirst().orElseGet(() -> 100)); //=>findFirstで獲得できないため、()-> 100 が実行され戻り値の100を取得する

orElseという名前について...

ifPresentというメソッドにちなんで命名されたと考えられる
ifPresentはvoidメソッドなので、メソッドチェーンでorElseと共存させることはできない。


// 以下はコンパイルエラー
ifPresent(System.out::println).orElse(0);
1
0
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
1
0