Iterating Over Two Arrays Simultaneously Using for Each Loop in Java

Iterating over two arrays simultaneously using for each loop in Java

The underlying problem is actually that you should tie both of the arrays together and iterate across just one array.

Here is a VERY simplistic demonstration - you should use getters and setters and you should also use a List instead of an array but this demonstrates the point:

class Student {
String name;
int mark;
}
Student[] students = new Student[10];

for (Student s : students) {
...
}

Can I iterate over two arrays at once in Java?

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];
...
}

Efficient way to iterate over two related ArrayLists?

The Answer by dreamcrash is correct: While your looping of a pair of arrays works, you should instead take advantage of Java as a OOP language by defining your own class.

Record

Defining such a class is even simpler in Java 16 with the new records feature. Write your class as a record when it’s main purpose is communicating data, transparently and immutably.

A record is very brief by default. The compiler implicitly creates the constructor, getters, equals & hashCode, and toString. You need only declare the type and name of each member field.

record ColorNoun ( String color , String noun ) {}

Use a record like a conventional class. Instantiate with new.

ColorNoun blueSky = new ColorNoun ( "Blue" , "Sky" ) ;

Note that a record can be declared locally within a method, or declared separately like a conventional class.

forEach loop through two arrays at the same time in javascript

Use the second parameter forEach accepts instead, which will be the current index you're iterating over:

n = [1,2,3,5,7,8,9,11,12,13,14,16,17,18,20,21,22];
n.forEach((element, index) => { console.log(element, index);});

How to Iterate through two ArrayLists Simultaneously?

You can use Collection#iterator:

Iterator<JRadioButton> it1 = category.iterator();
Iterator<Integer> it2 = cats_ids.iterator();

while (it1.hasNext() && it2.hasNext()) {
...
}

How can I use one forEach loop to iterate over two different arrays?

You can use concat to join them together, so:

var array1 = [1, 2, 3, 4];
var array2 = [5, 6, 7, 8];

array1.concat(array2).forEach(function(item){
console.log(item)
});

Prints 1, 2, 3, 4, 5, 6, 7, 8 on separate lines.



Related Topics



Leave a reply



Submit