The following example code demonstrates Iterators on Multiple Collections in Parallel in Java.
Here’s an example of how to demonstrate the iteration over multiple collections in parallel in Java.
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> names = Arrays.asList("John", "Jane", "Jim");
List<Integer> ages = Arrays.asList(30, 25, 35);
// Using Iterator
Iterator<String> nameIt = names.iterator();
Iterator<Integer> ageIt = ages.iterator();
System.out.println("Using Iterator:");
while (nameIt.hasNext() && ageIt.hasNext()) {
String name = nameIt.next();
Integer age = ageIt.next();
System.out.println(name + ", " + age);
}
// Using forEach and Lambda expression
System.out.println("\nUsing forEach and Lambda expression:");
Iterator<String> nameIt2 = names.iterator();
Iterator<Integer> ageIt2 = ages.iterator();
names.forEach(name -> {
if (nameIt2.hasNext() && ageIt2.hasNext()) {
Integer age = ageIt2.next();
System.out.println(name + ", " + age);
}
});
}
}
In this example, two collections names
and ages
are created to store the names and ages of people, respectively.
The first example demonstrates how to use two separate Iterator
objects to traverse the names
and ages
collections in parallel. The hasNext
method is used to check if there are more elements in each collection and the next
method is used to retrieve the next element in each collection.
The second example demonstrates how to use the forEach
method with a Lambda expression to traverse the names
collection, while using another Iterator
object to traverse the ages
collection in parallel.