LoginSignup
5
5

More than 5 years have passed since last update.

java.util.Stream#allMatch() を使うときの注意

Posted at
public static void main(String[] args) {

  boolean isAllOfFruitsAreApple_1 =
      Arrays.stream(new String[] {"apple", "apple"}).allMatch(s -> s.equals("apple"));

  System.out.println(isAllOfFruitsAreApple_1);

  boolean isAllOfFruitsAreApple_2 =
      Arrays.stream(new String[] {"apple", "orange"}).allMatch(s -> s.equals("apple"));

  System.out.println(isAllOfFruitsAreApple_2);

  boolean isAllOfFruitsAreApple_3 = Stream.empty().allMatch(s -> s.equals("apple"));

  System.out.println(isAllOfFruitsAreApple_3);
}

上記コードを見てどういう出力が得られると思いますか?

true
false
true

だと即答できた方は以降は読まなくて大丈夫です。

https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#allMatch-java.util.function.Predicate-

If the stream is empty then {@code true} is returned and the predicate is not evaluated.

とあるように、ストリームが空の場合は、Predicateは評価されずにtrueが返される仕様なので、ドキュメントあまり読まないマン(自分含む)の方は注意しないとハマるかもしれません。

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