Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java foreach loop with two arrays [duplicate]

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

like image 517
Declan McLeman Avatar asked Apr 16 '16 10:04

Declan McLeman


3 Answers

A workaround would be to use Streams

 Stream.concat(arr1.stream(),arr2.stream()).forEachOrdered(str -> {
   // for loop body
 });
like image 74
Sleiman Jneidi Avatar answered Nov 08 '22 16:11

Sleiman Jneidi


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());
} 
like image 9
Suresh Atta Avatar answered Nov 08 '22 17:11

Suresh Atta


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
like image 2
Saleem Avatar answered Nov 08 '22 15:11

Saleem