Check list empty java 8

Best practice to validate null and empty collection in Java

If you use the Apache Commons Collections library in your project, you may use the CollectionUtils.isEmpty and MapUtils.isEmpty[] methods which respectively check if a collection or a map is empty or null [i.e. they are "null-safe"].

The code behind these methods is more or less what user @icza has written in his answer.

Regardless of what you do, remember that the less code you write, the less code you need to test as the complexity of your code decreases.


That is the best way to check it. You could write a helper method to do it:

public static boolean isNullOrEmpty[ final Collection< ? > c ] { return c == null || c.isEmpty[]; } public static boolean isNullOrEmpty[ final Map< ?, ? > m ] { return m == null || m.isEmpty[]; }

If you use Spring frameworks, then you can use CollectionUtils to check against both Collections [List, Array] and Map etc.

if[CollectionUtils.isEmpty[...]] {...}

Video liên quan

Chủ Đề