どうも、ちょげ(@chogetarou)です。
Map(マップ)がnullもしくは空かどうか判定する方法を紹介します。
方法
Map(マップ)がnullもしくは空かチェックするには、isEmpty()を使います。
まず、「||
」の左辺に「map == null
」(mapは任意のMap)を指定します。
そして、「||
」の右辺にMapのisEmpty()を指定します。
map == null || map.isEmpty();
上記の条件式は、Mapがnullもしくは空ならば「true」、nullでも空でもなければ「False」を返します。
使用例
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Map<String, Integer> numbers = new HashMap<String, Integer>();
numbers.put("one", 1);
numbers.put("two", 2);
numbers.put("three", null);
numbers.put("four", 4);
numbers.put("five", null);
Map<Integer, Integer> empty = new HashMap();
Map<Integer, Boolean> empty2 = null;
System.out.println(isNullOrEmpty(numbers));
System.out.println(isNullOrEmpty(empty));
System.out.println(isNullOrEmpty(empty2));
}
public static boolean isNullOrEmpty( final Map< ?, ? > map ) {
return map == null || map.isEmpty();
}
}
出力:
false
true
true
コメント