1

For one array I can iterate like this:

for(String str:myStringArray){ } 

How can I iterate over two arrays at once? Because I am sure these two's length are equal.I want it like the following:

for(String attr,attrValue:attrs,attrsValue) { } 

But it's wrong.

Maybe a map is a good option in this condition, but how about 3 equal length arrays? I just hate to create index 'int i' which used in the following format:

for(int i=0;i<length;i++){ } 
3
  • Not with a syntax that elegant. You'll need either two iterators or two counters and a single loop. Commented Nov 17, 2014 at 5:41
  • Use a regular for loop with a counter instead of an enhanced for loop. Determine how many iterations you want total, then call the index in each array that you want. Commented Nov 17, 2014 at 5:41
  • 1
    Based on the names "attr" and "attrValue," is this conceptually a Map? Because there is a way to do this for a Map. Commented Nov 17, 2014 at 5:44

3 Answers 3

5

You can't do what you want with the foreach syntax, but you can use explicit indexing to achieve the same effect. It only makes sense if the arrays are the same length (or you use some other rule, such as iterating only to the end of the shorter array):

Here's the variant that checks the arrays are the same length:

assert(attrs.length == attrsValue.length); for (int i=0; i<attrs.length; i++) { String attr = attrs[i]; String attrValue = attrsValue[i]; ... } 
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, I updated my question, I just hate to create that 'int i'.
I didn't get anything concrete from your update, except that you "hate to create that i". Unfortunately that's the cleanest approach if you have separate arrays. Keep in the mind the clean foreach construct is creating the index based code under the covers anyway. The arrays are logically bound together, maybe you what you need is a single array of some class that combines the elements, from both arrays, attr and attrValue in your example.
2

You can do it old fashion way.

Assuming your arrays have same sizes:

for(int i = 0; i < array1.length; i++) { int el1 = array1[i]; int el2 = array2[i]; } 

In Scala there is an embedded zip function for Collections, so you could do something like

array1 zip array2 

but it's not yet ported to Java8 Collections.

Comments

1

Foreach loop has many advantages but there are some restriction are also there.

1: You can iterate only one class(which implements Iterable i/f) at one time.

2: You don't have indexing control. (use explicit counter for that.)

For your problem use legacy for loop.

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.