LoginSignup
5
1

More than 1 year has passed since last update.

【Java】CollectionUtilsを使ってコレクション内のnullチェックをする方法

Posted at

はじめに

今週は外部ライブラリであるApache Commons Collectionsを使ってコレクション内のnull・size0チェックをする方法をアウトプットします。

これまでの書き方

これまではnullPointerExceptionを回避するために、以下のように書いてきました。

List<String> list = new ArrayList<String>();
//listはnullが来る可能性があるとします。

if (list == null || list.size() == 0) {
  return true;
}

CollectionUtilsを使った書き方

CollectionUtils.isEmpty()メソッドを使用することで、null・size0チェックをひとまとめにすることが出来ます。
ただし、使用するためにはorg.apache.commons.collections4.*をimportする必要があります。
今後、コレクション内のnull・size0チェックはこの方法を使ってみようと思います。

import org.apache.commons.collections4.*

List<String> list = new ArrayList<String>();
//listはnullが来る可能性があるとします。

if (CollectionUtils.isEmpty(list)) {
  return true;
}

参照

CollectionUtils (Apache Commons Collections 4.4 API)

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