在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 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));
});

其他回答

虽然有很多其他的方法可以达到同样的效果,但我还是将我的方法分享给一些不满意的用户。我正在使用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));
});

恐怕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);
    }

没有,但你可以提供自己的柜台。

这样做的原因是for-each循环内部没有计数器;它基于Iterable接口,也就是说,它使用一个迭代器来遍历“集合”——这可能根本不是一个集合,实际上可能根本不是基于索引的东西(比如链表)。

我通常使用数组来解决这个问题

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
}

在Java 8中使用lambda和函数接口使得创建新的循环抽象成为可能。我可以通过索引和集合大小来循环一个集合:

List<String> strings = Arrays.asList("one", "two","three","four");
forEach(strings, (x, i, n) -> System.out.println("" + (i+1) + "/"+n+": " + x));

输出:

1/4: one
2/4: two
3/4: three
4/4: four

我实现如下:

   @FunctionalInterface
   public interface LoopWithIndexAndSizeConsumer<T> {
       void accept(T t, int i, int n);
   }
   public static <T> void forEach(Collection<T> collection,
                                  LoopWithIndexAndSizeConsumer<T> consumer) {
      int index = 0;
      for (T object : collection){
         consumer.accept(object, index++, collection.size());
      }
   }

可能性是无限的。例如,我创建了一个抽象,它只对第一个元素使用了一个特殊的函数:

forEachHeadTail(strings, 
                (head) -> System.out.print(head), 
                (tail) -> System.out.print(","+tail));

正确打印逗号分隔的列表:

one,two,three,four

我实现如下:

public static <T> void forEachHeadTail(Collection<T> collection, 
                                       Consumer<T> headFunc, 
                                       Consumer<T> tailFunc) {
   int index = 0;
   for (T object : collection){
      if (index++ == 0){
         headFunc.accept(object);
      }
      else{
         tailFunc.accept(object);
      }
   }
}

库将开始弹出来做这些事情,或者你可以自己编写。