带有两个数组的 Java foreach 循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36662834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java foreach loop with two arrays
提问by Declan McLeman
I have a simple question, can something like the following possibly be done on Java?
我有一个简单的问题,可以在 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.
我能想到的最好方法是使用单独的 for 循环,当 for 循环具有相同的内部代码时,这会进行冗余编码。
Another solution was to make an array of ArrayLists. This makes it easy to fulfil my intent, that is:
另一种解决方案是制作一个 ArrayLists 数组。这使我很容易实现我的意图,即:
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
提前致谢,德克兰
采纳答案by Suresh Atta
Not possible, at least with below Java 9. Here is a possible way
不可能,至少在 Java 9 以下是不可能的。这是一种可能的方法
i1= arr1.iterator();
i2= arr2.iterator();
while(arr1.hasNext() && arr2.hasNext())
{
ToDo1(arr1.next());
ToDo2(arr2.next());
}
回答by Balayesu Chilakalapudi
Not Possible, Try the below code
不可能,试试下面的代码
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
}
}
回答by Sleiman Jneidi
A workaround would be to use Streams
一种解决方法是使用 Streams
Stream.concat(arr1.stream(),arr2.stream()).forEachOrdered(str -> {
// for loop body
});
回答by Saleem
You can chain multiple collections together using Stream.of
and flatMap
in Java 8 and iterate over sequentially in order passed to Stream.of
您可以在 Java 8 中使用Stream.of
和 将多个集合链接在一起,flatMap
并按顺序迭代以传递给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