1

In the conventional loop, we could have as below, making single nested layer.

for (int i=0; listObject != null && i < listObject.size(); i++) {
    // Do whatever we want
}

However, using the below style for each loop, I'll need a double nested code: -

if (listObject != null) {
    for (Object object: listObject) {
        // Do whatever we want
    }
}

Is it possible to embed the listObject != null condition into the for-loop statement to make it single nested code?

Elye
  • 53,639
  • 54
  • 212
  • 474
  • Why do you need to check if `listObject` is null during each iteration of the loop? Is there code somewhere that might dereference it? – Damien Diehl Jan 13 '16 at 22:48
  • Same question IMO was already asked there: http://stackoverflow.com/questions/6077909/is-there-a-way-to-avoid-null-check-before-the-for-each-loop-iteration-starts – Rozart Jan 13 '16 at 22:48
  • The "null" check is a more typical case of example. It idea is, if we have another condition to check, is there a way to still make it single nested. I have provided my version of answer below. Thanks! – Elye Jan 13 '16 at 23:09
  • 2
    To have a flatter code structure, I may do a normalization first like `if(list==null) list=emptyList();` – ZhongYu Jan 13 '16 at 23:40

2 Answers2

3

Your second example is clear, easily understood code. There is nothing wrong with nesting a for loop in an if block. It's even more clear than your first example.

But if you insist on combining them, you can use the ternary operator to supply an empty list if listObject is null. Using Collections.emptyList means no iterations will take place and no NullPointerException will be thrown.

for (Object object : listObject == null ? Collections.emptyList() : listObject)

I don't think I would use code like this when a clear example such as your second example already exists, but this code does provide a way to get two colons inside a for loop.

rgettman
  • 176,041
  • 30
  • 275
  • 357
  • Thanks @rgettman. I'll give a tick to this answer given it's answering my question directly. I have my own version of approach though not as direct. Will write as one answer to this as well (check it out and comment if any). Thanks! – Elye Jan 13 '16 at 23:05
0

To make it concise on, while having a single nested loop, I decided to make it into function as below

void checkCondition(List<Object> listObject) {
   if (listObject == null) return;

   for (Object object: listObject) {
       // Do whatever
   }
}
Elye
  • 53,639
  • 54
  • 212
  • 474