139

Every time I have to iterate over a collection I end up checking for null, just before the iteration of the for-each loop starts. Like this:

if( list1 != null ){
    for(Object obj : list1){

    }
}

Is there a shorter way, so that we can avoid writing the "if" block ? Note: I am using Java 5, and will be stuck with it for sometime.

risingTide
  • 1,754
  • 7
  • 31
  • 60
rk2010
  • 3,481
  • 7
  • 27
  • 39
  • 6
    Like SLaks said, your collections should not be null instead their size be zero. In that case, the enhanced for loop doesn't error out. – asgs May 20 '11 at 21:55
  • you can remove the block of the if and it would have the same effect – ratchet freak May 20 '11 at 22:04
  • 2
    @ratchet I can't remove the "if" block. If in case the list1 is null, then there will be NullPointerException – rk2010 May 20 '11 at 22:10
  • I meant that you type `if(list1 != null)for(Object obj : list1){...}` in other words remove the curly braces around for this way you can keep it in one line – ratchet freak May 20 '11 at 22:15
  • @ratchet Interesting... but I probably won't get that pass the code review :) – rk2010 May 20 '11 at 22:17
  • I guess the right answer is that: there is no way to make it shorter. there are some techniques such as the ones in the comments, but I don't see myself using them. I think it's better to write a "if" block than to use those techniques. and yes.. before anybody mentions it yet again :) "ideally" the code should be desgined such that list should never be a null. – rk2010 May 20 '11 at 22:35
  • You need to show us more code. How are you getting a null list? – NomadMaker Aug 29 '20 at 23:49
  • This is not a foreach loop. Its an enhanced for loop. – Shiva kumar Jun 03 '21 at 17:49

10 Answers10

100

If possible, you should design your code such that the collections aren't null in the first place.

null collections are bad practice (for this reason); you should use empty collections instead. (eg, Collections.emptyList())

Alternatively, you could make a wrapper class that implements Iterable and takes a collections, and handles a null collection.
You could then write foreach(T obj : new Nullable<T>(list1))

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 3
    I am just one of the developers... a lowly ranked one at that :) – rk2010 May 20 '11 at 21:56
  • 3
    if you're using generics it's better to use Collections.emptyList() rather than Collections.EMPTY_LIST; it's type safe. – Steven Fines May 20 '11 at 22:04
  • @Dataknife More like it just does the casting for you. There are no generics types at runtime with either case, and the implementation of `emptyList()` internally contains the cast (with a suppression on unchecked too). – Edwin Buck Oct 14 '13 at 16:14
  • 1
    This turned out to be bad design for me. The place I placed them was then used by JAX - B to unmarshall data These lists are immutable and it would try and add to them. I think you should consider this too http://stackoverflow.com/questions/5552258/collections-emptylist-vs-new-instance – Abs Jun 04 '15 at 05:42
  • And empty list works great when you have the idea of a collection with nothing in it. That is subtly different than no collection; and, the difference can be significant. For example, when optional lists are represented as empty ones, you have to choose between handling it as a list or as nothing (the simplification removes one of the two options). This can be undesirable in some situations. – Edwin Buck Dec 04 '20 at 15:25
  • How is having an empty collection a good practice? Isn't this going to be using a lo t of memory? In applications where milliseconds matters this would be the best to do also? – Diego Ramos Mar 24 '22 at 23:54
54
public <T extends Iterable> T nullGuard(T item) {
  if (item == null) {
    return Collections.EmptyList;
  } else {
    return item;
  }
}

or, if saving lines of text is a priority (it shouldn't be)

public <T extends Iterable> T nullGuard(T item) {
  return (item == null) ? Collections.EmptyList : item;
}

would allow you to write

for (Object obj : nullGuard(list)) {
  ...
}

Of course, this really just moves the complexity elsewhere.

Edwin Buck
  • 69,361
  • 7
  • 100
  • 138
  • 18
    Good answer, but probably should be a static. – ykaganovich Apr 29 '13 at 18:41
  • 1
    It does not just "move the complexity elsewhere". It encapsulates the complexity in one place, so you don't have to write that null-checking code again and again. The question was how to make it shorter. The check has to be done **somewhere**. You are very humble, @edwin-buck – Ajoy Bhatia Apr 21 '20 at 21:37
  • public T nullGuard(T item) { if (item == null) { return Collections.EmptyList; } return item; } – corroborator Aug 28 '20 at 23:08
  • @corroborator Yes, that saves the "else" statement by doing a short-circuit return. It is an equivalent code flow. I updated to have an even smaller solution; but, really saving lines of text should be secondary in priority to easy to read code. Not sure what the style is in the place where this solution might be used; but, mimic it's style (not a personal one) if a dominant style exists. – Edwin Buck Aug 29 '20 at 23:19
43

It's already 2017, and you can now use Apache Commons Collections4

The usage:

for(Object obj : CollectionUtils.emptyIfNull(list1)){
    // Do your stuff
}
Fred Pym
  • 2,149
  • 1
  • 20
  • 29
37

I guess the right answer is that: there is no way to make it shorter. There are some techniques such as the ones in the comments, but I don't see myself using them. I think it's better to write a "if" block than to use those techniques. and yes.. before anybody mentions it yet again :) "ideally" the code should be desgined such that list should never be a null

gavenkoa
  • 45,285
  • 19
  • 251
  • 303
rk2010
  • 3,481
  • 7
  • 27
  • 39
31

In Java 8 there is another solution available by using java.util.Optional and the ifPresent-method.

Optional.ofNullable(list1).ifPresent(l -> l.forEach(item -> {/* do stuff */}));

So, not a solution for the exact problem but it is a oneliner and possibly more elegant.

wassgren
  • 18,651
  • 6
  • 63
  • 77
  • 4
    Java 8 `Optional` is a case of the cure being a bit worse than the disease. `Optional` is a verbose and clunky replacement for a simple null check. To be avoided, imo. – Charlie Reitzel Jan 31 '20 at 19:43
  • @CharlieReitzel absolutely! But if the code-base is very null-value-oriented, I find this approach working pretty well for me: Cleaner version of a null check. I would definitely recommend this `Optional.ofNullable()`. – Z-100 Apr 19 '23 at 12:46
  • Less code, less bugs. `if ( null != foo ) ...` looks _a lot_ cleaner to me than `Optional.ofNullable(foo).ifPresent( xfoo -> ... );` But, of course, you may feel differently. – Charlie Reitzel Apr 19 '23 at 18:39
17

Null check in an enhanced for loop

public static <T> Iterable<T> emptyIfNull(Iterable<T> iterable) {
    return iterable == null ? Collections.<T>emptyList() : iterable;
}

Then use:

for (Object object : emptyIfNull(someList)) { ... }
Community
  • 1
  • 1
gavenkoa
  • 45,285
  • 19
  • 251
  • 303
17

Apache Commons

for (String code: ListUtils.emptyIfNull(codes)) {

}           

Google Guava

for (String code: Optional.of(codes).get()) {

}
Kerem Baydoğan
  • 10,475
  • 1
  • 43
  • 50
7

How much shorter do you want it to be? It is only an extra 2 lines AND it is clear and concise logic.

I think the more important thing you need to decide is if null is a valid value or not. If they are not valid, you should write you code to prevent it from happening. Then you would not need this kind of check. If you go get an exception while doing a foreach loop, that is a sign that there is a bug somewhere else in your code.

unholysampler
  • 17,141
  • 7
  • 47
  • 64
  • 1
    unfortunately in many situation touching methods that gives these lists can create problems for me... It won't be the first time where I saw methods "expecting" null to be returned by other methods.. – rk2010 May 20 '11 at 22:02
  • I was wondering it could be shorter, because I recently came across some Groovy code that checks for null using "?".. forgot what its called. – rk2010 May 20 '11 at 22:03
  • The ternary operrator. – ggb667 Oct 19 '21 at 17:33
6

1) if list1 is a member of a class, create the list in the constructor so it's there and non-null though empty.

2) for (Object obj : list1 != null ? list1 : new ArrayList())

Chris
  • 820
  • 7
  • 22
  • interesting.. will be trying it out – rk2010 May 20 '11 at 21:59
  • 2
    Much better to use Collections.emptyList(). Why allocate something just to garbage collect it? – Edwin Buck Nov 07 '16 at 14:58
  • 1
    inspired like this comment I wrote at utility class : `public static List ofNullable(List list) {return list == null ? Collections.emptyList() : list;}` and then use: ` for (Object obj : ofNullable(list1)) {` – Nemo Dec 07 '21 at 10:18
3

Another Java 8+ way would be to create a forEach method that does not crash when using a null value:

public static <T> void forEach(Iterable<T> set, Consumer<T> action) {
    if (set != null) {
        set.forEach(action);
    }
}

The usage of the own defined foreach is close to the native Java 8 one:

ArrayList<T> list = null;

//java 8+ (will throw a NullPointerException)
list.forEach(item -> doSomething(...) );

//own implementation
forEach(list, item -> doSomething(...) );
Jacob van Lingen
  • 8,989
  • 7
  • 48
  • 78