在Java的for-each循环中有办法吗
for(String s : stringArray) {
doSomethingWith(s);
}
找出循环已经被处理的频率?
除了使用老的和众所周知的for(int i=0;I <边界;i++) - loop,是构造
int i = 0;
for(String s : stringArray) {
doSomethingWith(s);
i++;
}
在for-each循环中有这样一个计数器的唯一方法是什么?
在Java的for-each循环中有办法吗
for(String s : stringArray) {
doSomethingWith(s);
}
找出循环已经被处理的频率?
除了使用老的和众所周知的for(int i=0;I <边界;i++) - loop,是构造
int i = 0;
for(String s : stringArray) {
doSomethingWith(s);
i++;
}
在for-each循环中有这样一个计数器的唯一方法是什么?
当前回答
Sun正在为Java7考虑的一个变化是在foreach循环中提供对内部迭代器的访问。语法将是这样的(如果这是接受的):
for (String str : list : it) {
if (str.length() > 100) {
it.remove();
}
}
这是语法上的甜食,但显然有很多人对这个功能提出了要求。但是在它被批准之前,您必须自己计算迭代次数,或者使用带有Iterator的常规for循环。
其他回答
对于偶尔需要索引的情况,比如在catch子句中,我有时会使用indexOf。
for(String s : stringArray) {
try {
doSomethingWith(s);
} catch (Exception e) {
LOGGER.warn("Had some kind of problem with string " +
stringArray.indexOf(s) + ": " + s, e);
}
}
Sun正在为Java7考虑的一个变化是在foreach循环中提供对内部迭代器的访问。语法将是这样的(如果这是接受的):
for (String str : list : it) {
if (str.length() > 100) {
it.remove();
}
}
这是语法上的甜食,但显然有很多人对这个功能提出了要求。但是在它被批准之前,您必须自己计算迭代次数,或者使用带有Iterator的常规for循环。
虽然有很多其他的方法可以达到同样的效果,但我还是将我的方法分享给一些不满意的用户。我正在使用Java 8 IntStream特性。
1. 数组
Object[] obj = {1,2,3,4,5,6,7};
IntStream.range(0, obj.length).forEach(index-> {
System.out.println("index: " + index);
System.out.println("value: " + obj[index]);
});
2. 列表
List<String> strings = new ArrayList<String>();
Collections.addAll(strings,"A","B","C","D");
IntStream.range(0, strings.size()).forEach(index-> {
System.out.println("index: " + index);
System.out.println("value: " + strings.get(index));
});
我通常使用数组来解决这个问题
List<String> list = new ArrayList<String>();
final int[] counter = new int[1];
list.foreach( item -> {
list.get(counter[0]) // code here that can use counter[0] for counter value
counter[0]++; // increment the counter
}
没有,但你可以提供自己的柜台。
这样做的原因是for-each循环内部没有计数器;它基于Iterable接口,也就是说,它使用一个迭代器来遍历“集合”——这可能根本不是一个集合,实际上可能根本不是基于索引的东西(比如链表)。