I have a simple question, can something like the following possibly be done on Java?
ArrayList<String> arr1 = new ArrayList<String>();
ArrayList<String> arr2 = new ArrayList<String>();
// Processing arrays, filling them with data
for(String str : arr1, arr2) {
//Do stuff
}
Where the intent is to iterate through the first array then the next array.
The best I can figure is to either use separate for loops which makes for redundant coding when the for loops have identical internal code.
Another solution was to make an array of ArrayLists. This makes it easy to fulfil my intent, that is:
ArrayList<ArrayList<String>> arr = new ArrayList<ArrayList<String>>();
// Initialising arr and populating with data
for(ArrayList<String> tempArr : arr) {
for(String str : tempArr) {
//Do stuff
}
}
But this makes for unreadable code. Is there a clean way of doing the latter where I don't lose the names of the separate arrays?
Thanks in advance, Declan
A workaround would be to use Streams
Stream.concat(arr1.stream(),arr2.stream()).forEachOrdered(str -> {
// for loop body
});
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());
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With