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]
5 comments:
Post a Comment
Individuals who comment on FromDev at regular basis, will be rewarded in Top Commenter section. (Comments are selectively moderated so please do not spam)