Is there a way to avoid null check before the for-

2019-01-13 01:38发布

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.

9条回答
疯言疯语
2楼-- · 2019-01-13 02:18

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

The usage:

for(Object obj : CollectionUtils.emptyIfNull(list1)){
    // Do your stuff
}
查看更多
何必那么认真
3楼-- · 2019-01-13 02:18

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)) { ... }
查看更多
时光不老,我们不散
4楼-- · 2019-01-13 02:26

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.

查看更多
霸刀☆藐视天下
5楼-- · 2019-01-13 02:27

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())

查看更多
我想做一个坏孩纸
6楼-- · 2019-01-13 02:32

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

查看更多
我欲成王,谁敢阻挡
7楼-- · 2019-01-13 02:37
public <T extends Iterable> T nullGuard(T item) {
  if (item == null) {
    return Collections.EmptyList;
  } else {
    return item;
  }
}

would allow you to write

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

Of course, this really just moves the complexity elsewhere.

查看更多
登录 后发表回答