AJW
AJW

Reputation: 5863

Multiple for loops

Is it possible to combine multiple for loops into one loop in Java?

e.g, I have

for (i : lista)
{
 //do something
}

for (j : listb)
{
 //do something
}

is it possible to combine both in one?

Upvotes: 2

Views: 7984

Answers (5)

isharailanga
isharailanga

Reputation: 595

Nested for loops

for(int i=0;i<10;i++){
        for(int j=0;j<0;j++){

        }
}

Upvotes: 0

juergen d
juergen d

Reputation: 204766

Not too long ago I had a task where I needed that.

I parsed every pixel of an image and generated in the same for loop another image.

for(int a = 0, b = 0; a < 10 && b < 20; a++, b+=2) 
{ 
    /*...*/ 
}

Upvotes: 0

Amir Afghani
Amir Afghani

Reputation: 38531

The most readable way to do this is to combine the two lists into one and iterate.

List<String> combinedList = new ArrayList<String>(listOne);
combinedList.addAll(listTwo);

Upvotes: 0

Nicolas78
Nicolas78

Reputation: 5144

I think your question only makes sense when lista and listb are of equal size, right? Then you could say something like

for (int k=0; k<lista.length; k++)
{
  int i = lista[k];
  int j = listb[k];
  // do something
}

Upvotes: 8

Ted Hopp
Ted Hopp

Reputation: 234795

You can nest the loops, but the only way to concatenate them is to write one after the other.

Upvotes: 0

Related Questions