在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循环中有这样一个计数器的唯一方法是什么?


当前回答

最佳和优化的解决方案是做以下事情:

int i=0;

for(Type t: types) {
  ......
  i++;
}

其中Type可以是任何数据类型,types是应用于循环的变量。

其他回答

如果你在for-each循环中需要一个计数器,你就必须数自己。据我所知,没有内置的计数器。

恐怕foreach不行。但我可以给你一个简单的老式for循环:

    List<String> l = new ArrayList<String>();

    l.add("a");
    l.add("b");
    l.add("c");
    l.add("d");

    // the array
    String[] array = new String[l.size()];

    for(ListIterator<String> it =l.listIterator(); it.hasNext() ;)
    {
        array[it.nextIndex()] = it.next();
    }

注意,List接口允许您访问它。nextindex()。

(编辑)

到你改变的例子:

    for(ListIterator<String> it =l.listIterator(); it.hasNext() ;)
    {
        int i = it.nextIndex();
        doSomethingWith(it.next(), i);
    }

Java 8引入了Iterable#forEach() / Map#forEach()方法,与“经典的”for-each循环相比,该方法对于许多Collection / Map实现更有效。但是,在这种情况下也不提供索引。这里的技巧是在lambda表达式之外使用AtomicInteger。注意:lambda表达式中使用的变量必须有效为final,这就是为什么我们不能使用普通int类型。

final AtomicInteger indexHolder = new AtomicInteger();
map.forEach((k, v) -> {
    final int index = indexHolder.getAndIncrement();
    // use the index
});

还有另一种方法。

如果您编写了自己的Index类和一个静态方法,该方法在该类的实例上返回Iterable,那么您可以

for (Index<String> each: With.index(stringArray)) {
    each.value;
    each.index;
    ...
}

其中实现With。索引是这样的

class With {
    public static <T> Iterable<Index<T>> index(final T[] array) {
        return new Iterable<Index<T>>() {
            public Iterator<Index<T>> iterator() {
                return new Iterator<Index<T>>() {
                    index = 0;
                    public boolean hasNext() { return index < array.size }
                    public Index<T> next() { return new Index(array[index], 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
}