Java foreach loop with two arrays

I have a simple question, can there be something like the following in 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 } 

If the goal is to iterate over the first array, then the next array.

The best I can understand is to either use separate loops that do redundant coding when the for loops have identical inner code.

Another solution was to create an array of ArrayLists. This facilitates the fulfillment of my intentions, 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 it does unreadable code. Is there a clean way to do the latter where I don't lose the names of individual arrays?

Thanks in advance, Declan

+7
java arraylist arrays loops foreach
source share
4 answers

Impossible at least below Java 9. Here is a possible way

 i1= arr1.iterator(); i2= arr2.iterator(); while(arr1.hasNext() && arr2.hasNext()) { ToDo1(arr1.next()); ToDo2(arr2.next()); } 
+4
source share

A workaround would be to use Streams

  Stream.concat(arr1.stream(),arr2.stream()).forEachOrdered(str -> { // for loop body }); 
+2
source share

You can link multiple collections together using Stream.of and flatMap in Java 8 and flatMap through the sequence in order to go 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); }); 

The code above will print

 Hello world 
+1
source share

Impossible, try the code below

 List<String> arr1=new ArrayList<String>(); List<String> arr2==new ArrayList<String>(); List<ArrayList<String>> arrList=new ArrayList<ArrayList<String>>(); arrList.add(arr1); arrList.add(arr2); for(ArrayList<String> strlist : arrList) { for(String s:strlist){ // process array } } 
0
source share

All Articles