JavaでApache CommonsのUtilsクラスを使って各型のnullと空をチェックする方法

技術

はじめに

こんにちは!さいけです。

今回は、「JavaでApache CommonsのUtilsクラスを使って各型のnullと空をチェックする方法」について紹介します。

JavaでApache CommonsのUtilsクラスを使って各型のnullと空をチェックする方法

Apache CommonsのUtilsクラスのisEmptyメソッドを使って各型のnullと空のチェックができます。

今回紹介に使う型は以下のとおりです。

  • String
  • Array
  • List
  • Map

前提

また、前提の話になりますが、チェックする型によって依存関係が違うことに注意してください。

  • String、Arrayのチェックをしたい場合はapache.commons.lang3を利用します。
    • gradleに追加する場合は以下を追加
implementation('org.apache.commons:commons-lang3:3.9')
  • List、Mapのチェックをしたい場合はapache.commons.collections4を利用します。
    • gradleに追加する場合は以下を追加
implementation('org.apache.commons:commons-collections4:4.4')

では、それぞれ紹介していきます。

文字列のnullと空チェック

// 変数の準備
// 文字列あり
String stringHoge = "Hoge";
// 空文字あり
String stringEmpty = "";
// null
String stringNull = null;

// 検証
// false
System.out.println(StringUtils.isEmpty(stringHoge));
// true
System.out.println(StringUtils.isEmpty(stringEmpty));
// true
System.out.println(StringUtils.isEmpty(stringNull));

配列のnullと空チェック

// 変数の準備
// 配列あり
int[] arrayHoge = new int[1];
// 空のarray(sizeが0)
int[] arrayEmpty = new int[]{};
// null
int[] arrayNull = null;

// 検証
// false
System.out.println(ArrayUtils.isEmpty(arrayHoge));
// true
System.out.println(ArrayUtils.isEmpty(arrayEmpty));
// true
System.out.println(ArrayUtils.isEmpty(arrayNull));

Listのnullと空チェック

// 変数の準備
// list要素あり
List<Integer> listHoge = new ArrayList<>();
listHoge.add(1);
// 空のlist(sizeが0)
List<Integer> listEmpty = new ArrayList<>();
// null
List<Integer> listNull = null;

// 検証
// false
System.out.println(CollectionUtils.isEmpty(listHoge));
// ture
System.out.println(CollectionUtils.isEmpty(listEmpty));
// true
System.out.println(CollectionUtils.isEmpty(listNull));

Mapのnullと空チェック

// 変数の準備
// map要素あり
Map<Integer, String> mapHoge = new HashMap<>();
mapHoge.put(1, "Hello");
// 空のmap(sizeが0)
Map<?, ?> mapEmpty = new HashMap<>();
// null
Map<?, ?> mapNull = null;

// 検証
// false
System.out.println(MapUtils.isEmpty(mapHoge));
// true
System.out.println(MapUtils.isEmpty(mapEmpty));
// true
System.out.println(MapUtils.isEmpty(mapNull));

👍🎉

おわりに

今回は「JavaでApache CommonsのUtilsクラスを使って各型のnullと空をチェックする方法」について紹介しました。

Apache CommonsのUtilsクラスのisEmptyメソッドを使えば、if(hoge == null || hoge.equals(“”))みたいな式をif(StringUtils.isEmpty(hoge))に書き換えることができます。これにより、チェック処理を書く際の漏れが起きにくくなります。

ぜひ、役立ててみてください。

それでは\(^o^)/

コメント

タイトルとURLをコピーしました