Monday 20 April 2020

How to check whether a collection is null or empty?

Below snippet return true if the collection is null or empty.

public static boolean isCollectionNullOrEmpty(Collection<?> collection) {
         return collection == null || collection.isEmpty();
}

App.java
package com.sample.app;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;

public class App {

	public static boolean isCollectionNullOrEmpty(Collection<?> collection) {
		return collection == null || collection.isEmpty();
	}

	public static void main(String args[]) {
		System.out.println("Is list empty : " + isCollectionNullOrEmpty(null));
		System.out.println("Is list empty : " + isCollectionNullOrEmpty(Collections.EMPTY_LIST));
		System.out.println("Is list empty : " + isCollectionNullOrEmpty(Arrays.asList(2, 3, 5)));
	}

}

Output
Is list empty : true
Is list empty : true
Is list empty : false


You may like

No comments:

Post a Comment