Java

Java - List의 Null 체크하는 방법 (CollectionUtils)

codeManager 2022. 7. 27. 19:30
반응형

TL;DR

CollectionsUtils.isEmpty() 를 사용해서 List의 Null 체크하자.

 

 

 

List Null 체크하는 방법

 

1. List.isEmpty()

import java.util.Arrays;
import java.util.List;

class Example {
    public static void main(String[] args) {
        List<String> list = Arrays.asList();
        System.out.println(list.isEmpty());
    }
}

list 객체에 isEmpty()를 호출해서 empty인지 체크할 수 있다.

 

그러나 list가 null일 경우 NullPointerException이 발생한다.

 

import java.util.Arrays;
import java.util.List;

class Example {
    public static void main(String[] args) {
        List<String> list = null;
        System.out.println(list.isEmpty());
    }
}

 

결과

Exception in thread "main" java.lang.NullPointerException
	at Example.main(Example.java:9)

 

2. CollectionUtils.isEmpty()

NullPointerException을 방지하려면 CollectionUtils.isEmpty() 를 사용하면 된다.

org.springframework.util의 CollectionUtils, org.apache.commons.collections4의 CollectionUtils가 있다.

여러가지 CollectionUtils 중에 좋은 것을 사용하면 된다.

 

CollectionUtils.isEmpty()를 사용했을 때 장점은 NullPointerException을 방지할 수 있다는 점이다.

 

public static void main(String[] args) {
    List<String> list = null;
    System.out.println(CollectionUtils.isEmpty(list));
}

 

이렇게 코드를 작성하면 결과가 true로 정상적으로 나온다.

 

 

참고

https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/CollectionUtils.html

 

CollectionUtils (Apache Commons Collections 4.4 API)

Returns a Collection containing the exclusive disjunction (symmetric difference) of the given Iterables. The cardinality of each element e in the returned Collection will be equal to max(cardinality(e,a),cardinality(e,b)) - min(cardinality(e,a), cardinalit

commons.apache.org

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/util/CollectionUtils.html

 

CollectionUtils (Spring Framework 5.3.22 API)

Check whether the given Collection contains the given element instance. Enforces the given instance to be present, rather than returning true for an equal element as well.

docs.spring.io

 

반응형