Elye
Elye

Reputation: 60261

Can we add additional stopping condition in iterator for-loop?

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?

Upvotes: 1

Views: 101

Answers (2)

Elye
Elye

Reputation: 60261

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
   }
}

Upvotes: 0

rgettman
rgettman

Reputation: 178303

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.

Upvotes: 3

Related Questions