Good programming practices

Iterating over non null elements only

October 27th, 2011

Since Java 5 in this language exists very useful “foreach” statement. But if collection contains null elements, iterator will also return null. If code doesn’t check against null, this may cause a NullPointerException. So I made a simple class based on Decorator Design Pattern. It just wraps an Iterable or Iterator and return only non null values.

  1. public static void main(String[] args) {
  2. //a collection which contains null
  3. List<String> list = Arrays.asList(new String[]{"a", "b", null, "d"});
  4. System.out.println("NonNullIterable");
  5. for (String s : new NonNullIterable<>(list)) {
  6. System.out.print(s.toUpperCase());//this will print "ABC"
  7. }
  8. System.out.println("\nNormal Iterable");
  9. for (String s : list) {
  10. try {
  11. System.out.print(s.toUpperCase());
  12. } catch (NullPointerException e) {
  13. System.out.println("\nNullPointerException have been thrown");
  14. }
  15. }
  16. }

The output is below:
  1. NonNullIterable
  2. ABD
  3. Normal Iterable
  4. AB
  5. NullPointerException have been thrown
  6. D

This class may be used when you iterate using “foreach” or other loop (e.g. while). It makes code safer and more readable if you don’t care about null values.

You can see source code of NonNullIterable and the JUnit4 test on GitHub. There are no dependencies, except FindBugs annotation, which may be helpful when you analyses your application with this tool.

Leave a Response

You must be logged in to post a comment.