Example Code

Java Collection Utility methods – Trim/notNull for Collection

1 Mins read

Similar to the trim utility method for Array. below is another simple but useful Java Collection Utility/Util method, which can be used to trim/remove all null Object values in a Collection object. Doing this would eliminate a null check on every element in collection. This method returns null value if the input Collection itself is null. We can call this as trim of Collection, as it will return all not null objects in the result(trimming the size of Collection).

A notNull method for simple object is already a common utility method, which is used by many programmers now. Checking Collection with the same notNull can also be a good idea. I am not sure how much performance boost we can get by doing this but I am open to thoughts on it. Please share your comment with us.

Below is the implementation of notNull method for collection and its unit test methods for java.util.List and java.util.Set implementations.

/**
* This Collection utility or util method can be used to trim all the null
* values in the collection. For a collection with data {"1", "2", null,
* "3","4"} the output will be {"1", "2", "3","4"}
* 
* @param values
* @return Collection
*/
@SuppressWarnings("unchecked")
public static Collection notNull(final Collection values) {
if (values == null) {
return null;
}
Iterator colItr = values.iterator();
while (colItr.hasNext()) {
Object obj = colItr.next();
if (obj == null) {
colItr.remove();
}
}
return values;
}

Above method should consistently behave for all type of collections. Below are the testing results for above method when tested for a Set.

private static void testSetNotNull() {
Collection hs = new HashSet();
hs.add("1");
hs.add("2");
hs.add("3");
hs.add(null);
hs.add("4");
System.out.println(notNull(hs));
}

Output for above test method is as shown below, (remember that Set doesn’t guarantee sequence of objects)

[3, 2, 1, 4]

Same test is run for a List and the results are as expected.

private static void testListNotNull() {
List l = new ArrayList();
l.add("1");
l.add("2");
l.add("3");
l.add(null);
l.add("4");
System.out.println(notNull(l));
}

Output for above test method is as shown below

[1, 2, 3, 4]
trim values in java, trim collection, trim list, trim java util ArrayList, trim strings in collection, trim collection size

Leave a Reply

Your email address will not be published. Required fields are marked *