0

How can I iterate through two arrays at the same time without nested for loops in Java ? In pseudo code, it would be:

for each colorname in listOfColourNames and for each colorcode in listOfColourCodes
{
    print (colorname + " : " + colorcode);
}

Is that even possible to do this in Java ?

0poss
  • 153
  • 1
  • 8
  • 1
    Sure this is possible, just use the traditional way using an index, i.e. `for( int i = 0; i < Math.min(listOfColourNames .length, listOfColourCodes.length); i++) { ... }`. One note though: since the data seems to be related _I'd recommend not using 2 arrays_ since those can get easily out of sync (e.g. if you sort one of the arrays). Use 1 array of elements that hold both values (or yet better a list). – Thomas Feb 20 '19 at 11:05

1 Answers1

0

You may use an external dummy index, e.g.

for (int i=0; i < listOfColourNames.length; ++i) {
    System.out.println(listOfColourNames[i] + " : " + listOfColourCodes[i]);
}

Your question only makes good sense if both array would have the same length. If not, then you would only be able to cover both arrays up to the smaller length of the two.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360