0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Javaでの配列判定・比較まとめ(ラムダ式とArrays.equals)

Posted at

Javaで配列の中身を確認したり比較する際、Stream APIやArraysクラスを活用するとシンプルに書けます。ここではよくあるケースを例に、Qiita向けにまとめます。

配列の中に0以外の値があるかチェックする

anyMatch を使う場合

int[] array = {0, 0, 3, 0};

boolean hasNonZero = Arrays.stream(array).anyMatch(v -> v != 0);
System.out.println(hasNonZero); // true

anyMatch:条件を1つでも満たす要素があれば true を返す
0以外の値があるかを確認するのに便利

allMatch を使う場合

int[] array = {1, 2, 3};

boolean allNonZero = Arrays.stream(array).allMatch(v -> v != 0);
System.out.println(allNonZero); // true

allMatch:全ての要素が条件を満たす場合のみ true を返す
配列のすべてが0でないかを確認したい場合に使用

配列の比較

配列同士の等価比較
Arrays.equals(a, b) を使う場合

int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
int[] c = {1, 2, 4};

System.out.println(Arrays.equals(a, b)); // true
System.out.println(Arrays.equals(a, c)); // false

配列の 中身の順序と値 を比較する
配列の型が異なる場合はコンパイルエラー

array1.equals(array2) を使う場合

int[] a = {1, 2, 3};
int[] b = {1, 2, 3};

System.out.println(a.equals(b)); // false

これは 参照比較 になる
中身が同じでも、配列オブジェクトが異なれば false になる
基本的に配列の中身を比較したい場合は Arrays.equals を使う

まとめ

方法 用途 戻り値 備考
Arrays.stream(array).anyMatch(v -> 条件) 配列に条件を満たす要素があるか boolean 条件を1つでも満たせばtrue
Arrays.stream(array).allMatch(v -> 条件) 配列の全要素が条件を満たすか boolean 条件を全て満たす場合のみtrue
Arrays.equals(a, b) 配列の中身を比較 boolean 中身と順序をチェック
array1.equals(array2) 配列オブジェクトの参照を比較 boolean 中身は無視、参照が同じ場合のみtrue
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?