Java foreach loop with two arrays
You can chain multiple collections together using Stream.of
and flatMap
in Java 8 and iterate over sequentially in order passed to Stream.of
Stream.of(s1, s2 ...).flatMap(s -> s)
Example:
ArrayList<String> arr1 = new ArrayList<>();
ArrayList<String> arr2 = new ArrayList<>();
arr1.add("Hello");
arr2.add("World");
Stream.of(arr1.stream(), arr2.stream()).flatMap(s -> s).forEach(s1 -> {
System.out.println(s1);
});
Code above will print
Hello
world
Not possible, at least with below Java 9. Here is a possible way
i1= arr1.iterator();
i2= arr2.iterator();
while(i1.hasNext() && i2.hasNext())
{
ToDo1(i1.next());
ToDo2(i2.next());
}
A workaround would be to use Streams
Stream.concat(arr1.stream(),arr2.stream()).forEachOrdered(str -> {
// for loop body
});