LoginSignup
10
11

More than 5 years have passed since last update.

Listの全要素が指定の値で埋められているか調べる

Last updated at Posted at 2015-04-21

javaのList型変数の全要素が、指定した値で埋められているか調べるにはどうしたらいいか?

そんなロジックを書かなければいけない状況に出くわすのが稀だけど(設計自体見なおした方がいい可能性が高い)、仕事でListの全要素が空文字列かどうか判定しなければいけない状況に出くわしたのでメモ。

Collections#frequency(Collection<?>, Object)(since 1.5)で一致する要素数が調べられるので、Listのサイズと比較すれば判定できる。

関連:指定サイズ分固定値で埋めたListの生成方法

空文字列で埋められているか?

List<String> lst = new ArrayList<>(Collections.nCopies(3, ""));

// 判定
System.out.println(Collections.frequency(lst, "") == lst.size());
// -> true

System.out.println(String.format("値[%s] 一致数[%d/%d]",
    lst,
    Collections.frequency(lst, ""),
    lst.size()));
// -> 値[[, , ]] 一致数[3/3]

以下おまけ

指定の数値で埋められているか?

List<Integer> lst = new ArrayList<>(Collections.nCopies(3, 5));

System.out.println(Collections.frequency(lst, 5) == lst.size());
// -> true

nullで埋められているか?

List<String> lst = Arrays.asList(new String[3]);

System.out.println(Collections.frequency(lst, null) == lst.size());
// -> true

指定したインスタンスで埋められているか?

List<Integer> ins = new ArrayList<>(Arrays.asList(new Integer[]{1,2,3}));
List<List<Integer>> lst = new ArrayList<>(Collections.nCopies(3, ins));
ins.add(4);

System.out.println(Collections.frequency(lst, ins) == lst.size());
// -> true

※コードはjava 7で書いています

10
11
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
10
11