Java 中的新 for 循环可以与两个变量一起使用吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18045351/
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
Can the new for loop in Java be used with two variables?
提问by dogfish
We can use the old for loop (for(i = 0, j = 0; i<30; i++,j++)
) with two variables
Can we use the for-each loop (or the enhanced for loop) in java (for(Item item : items)
with two variables? What's the syntax for that?
我们可以使用for(i = 0, j = 0; i<30; i++,j++)
带有两个变量的旧 for 循环 ( )我们可以在 java 中使用 for-each 循环(或增强的 for 循环)(for(Item item : items)
带有两个变量?它的语法是什么?
采纳答案by Marko Topolnik
Unfortunately, Java supports only a rudimentary foreachloop, called the enhanced for loop. Other languages, especially FP ones like Scala, support a construct known as list comprehension(Scala calls it for comprehension) which allows nested iterations, as well as filtering of elements along the way.
不幸的是,Java 仅支持基本的foreach循环,称为增强的 for 循环。其他语言,尤其是像 Scala 这样的 FP 语言,支持一种称为列表理解的结构(Scala 将其称为理解),它允许嵌套迭代以及沿途过滤元素。
回答by Tala
No you can't. It is syntactic sugar for using Iterator. Refer herefor a good answer on this issue.
不,你不能。它是使用Iterator 的语法糖。有关此问题的好答案,请参阅此处。
You need to have an object that contains both variables.
您需要有一个包含这两个变量的对象。
It can be shown on a Map object for example.
例如,它可以显示在 Map 对象上。
for (Map.Entry<String,String> e: map.entrySet()) {
// you can use e.getKey() and e.getValue() here
}
回答by zapl
The foreach loop assumes that there is only one collection of things. You can do something for each element per iteration. How would you want it to behave that if you could iterate over two collections at once? What if they have different lenghts?
foreach 循环假设只有一个事物集合。您可以在每次迭代中为每个元素做一些事情。如果您可以一次迭代两个集合,您希望它如何表现?如果它们有不同的长度怎么办?
Assuming that you have
假设你有
Collection<T1> collection1;
Collection<T2> collection2;
You could write an iterable wrapper that iterates over both and returns some sort of merged result.
您可以编写一个可迭代的包装器,它对两者进行迭代并返回某种合并的结果。
for(TwoThings<T1, T2> thing : new TwoCollectionWrapper(collection1, collection2) {
// one of them could be null if collections have different length
T1 t1 = thing.getFirst();
T2 t2 = thing.getSecond();
}
That's the closest what I can think of but I don't see much use for that. If both collections are meant to be iterated together, it would be simpler to create a Collection<TwoThings>
in the first place.
这是我能想到的最接近的,但我认为它没有多大用处。如果两个集合都打算一起迭代,那么首先创建 a 会更简单Collection<TwoThings>
。
Besides iterating in parallel you could also want to iterate sequentially. There are implementations for that, e.g. Guava's Iterables.concat()
除了并行迭代之外,您还可能希望按顺序迭代。有一些实现,例如 Guava 的Iterables.concat()
回答by Jens Schauder
The simple answer "No" is already given. But you could implement taking two iterators as argument, and returning Pairs of the elements coming from the two iterators. Pair being a class with two fields. You'd either have to implement that yourself, or it is probably existent in some apache commons or similar lib.
已经给出了简单的答案“否”。但是您可以实现将两个迭代器作为参数,并返回来自两个迭代器的元素对。Pair 是一个具有两个字段的类。您要么必须自己实现它,要么它可能存在于某些 apache 公共资源或类似的库中。
This new Iterator could then be used in the foreach loop.
然后可以在 foreach 循环中使用这个新的迭代器。
回答by ajuser
The following should have the same (performance) effect that you are trying to achieve:
以下应具有与您尝试实现的(性能)相同的效果:
List<Item> aItems = new List<Item>();
List<Item> bItems = new List<Item>();
...
Iterator aIterator = aItems.iterator();
Iterator bIterator = bItems.iterator();
while (aIterator.hasNext() && bIterator.hasNext()) {
Item aItem = aIterator.next();
Item bItem = bIterator.next();
}
回答by sravan
I had to do one task where I need to collect various data from XML and store in SET interface and then output them to a CSV file.
我不得不做一项任务,我需要从 XML 收集各种数据并存储在 SET 接口中,然后将它们输出到 CSV 文件。
I read the data and stored it in Set interface object as x,y,z.
我读取数据并将其存储在 Set 接口对象中作为 x,y,z。
For CSV file header, I used string buffer to hold the headers String buffer
对于 CSV 文件标题,我使用字符串缓冲区来保存标题 字符串缓冲区
StringBuffer buffer = new StringBuffer("");
buffer.append("FIRST_NAME,LAST_NAME,ADDRESS\r\n")
Set<String> x = new HashSet<String>();
Set<String> y = new HashSet<String>();
Set<String> z = new HashSet<String>();
....
....
Iterator iterator1 = x.iterator()
Iterator iterator2 = y.iterator()
Iterator iterator3 = z.iterator()
while(iterator1.hasNext() && iterator2.hasNext() && iterator3.hasNext()){
String fN = iterator1.next()
String lN = iterator2.next()
String aDS = iterator3.next()
buffer.append(""+fN+","+lN+","+aDS+"\r\n")
}