334

Is there a way in Java's for-each loop

for(String s : stringArray) {
  doSomethingWith(s);
}

to find out how often the loop has already been processed?

Aside from using the old and well-known for(int i=0; i < boundary; i++) - loop, is the construct

int i = 0;
for(String s : stringArray) {
  doSomethingWith(s);
  i++;
}

the only way to have such a counter available in a for-each loop?

2
  • 2
    Another pity is that you cannot use the loop variable outside the loop, Type var = null; for (var : set) dosomething; if (var != null) then ...
    – Val
    Sep 5, 2013 at 12:45
  • @Val unless the reference is effective final. See my answer for how to use this feature
    – rmuller
    Oct 18, 2016 at 19:05

16 Answers 16

247

No, but you can provide your own counter.

The reason for this is that the for-each loop internally does not have a counter; it is based on the Iterable interface, i.e. it uses an Iterator to loop through the "collection" - which may not be a collection at all, and may in fact be something not at all based on indexes (such as a linked list).

5
  • 8
    Ruby has a construct for this and Java should get it too... for(int idx=0, String s; s : stringArray; ++idx) doSomethingWith(s, idx); Mar 6, 2014 at 22:37
  • 2
    FYI @NicholasDiPiazza there is an each_with_index loop method for Enumerable in Ruby. See apidock.com/ruby/Enumerable/each_with_index
    – saywhatnow
    Dec 4, 2015 at 1:40
  • @saywhatnow yeah that's what i meant sorry - not sure what i was smoking when i made the previous comment Dec 4, 2015 at 19:30
  • 5
    "The reason for this is that the for-each loop internally does not have a counter". Should be read as "Java developers didn't care to let programmer specify index variable with initial value inside for loop", something like for (int i = 0; String s: stringArray; ++i)
    – izogfif
    Jun 9, 2018 at 4:28
  • 1
    Why can't we maintain an index/counter for anything which is Iterable? LinkedList is not based on indexes but we still have ListIterator which maintains a counter internally while iterating on it. If we are iterating on something that means we have n number of items, be it any format/DS. Isn't it? Any example where an index can't be maintained will be helpful. Thanks. Jul 29, 2021 at 20:12
77

There is another way.

Given that you write your own Index class and a static method that returns an Iterable over instances of this class you can

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

Where the implementation of With.index is something like

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++); }
                    ...
                }
            }
        }
    }
}
11
  • 8
    Neat idea. I would have upvoted had it not been for short lived object creation of the Index class.
    – mR_fr0g
    Jun 11, 2013 at 14:44
  • 6
    @mR_fr0g don't worry, I benchmarked this and creating all these objects is not any slower than reusing the same object for each iteration. The reason is that all these objects are allocated in eden space only and never life long enough to reach the heap. So allocating them is as fast as e.g. allocating local variables.
    – akuhn
    Jun 12, 2013 at 21:55
  • 1
    @akuhn Wait. Eden space does not mean that no GC is reaquired. Quite the opposite, you need to invoke constructor, scan sooner with GC and finalize. This not only loads CPU but also invalidates the cache all the time. Nothing like this is necessary for local variables. Why do you say that this is "the same"?
    – Val
    Sep 1, 2013 at 14:03
  • 9
    If you are worried about performance of short lived objects like this, you are doing it wrong. Performance should be the LAST thing to worry about... readability the first. This is actually a pretty good construct.
    – Bill K
    Nov 16, 2013 at 8:08
  • 5
    I was going to say I don't really understand the need to debate when the Index instance can be created once and reused/updated, just to moot the argument and make everyone happy. However, in my measurements, the version that creates a new Index() each time performed more than twice as fast on my machine, about equal to a native iterator running the same iterations. Dec 21, 2013 at 21:03
66

The easiest solution is to just run your own counter thus:

int i = 0;
for (String s : stringArray) {
    doSomethingWith(s, i);
    i++;
}

The reason for this is because there's no actual guarantee that items in a collection (which that variant of for iterates over) even have an index, or even have a defined order (some collections may change the order when you add or remove elements).

See for example, the following code:

import java.util.*;

public class TestApp {
  public static void AddAndDump(AbstractSet<String> set, String str) {
    System.out.println("Adding [" + str + "]");
    set.add(str);
    int i = 0;
    for(String s : set) {
        System.out.println("   " + i + ": " + s);
        i++;
    }
  }

  public static void main(String[] args) {
    AbstractSet<String> coll = new HashSet<String>();
    AddAndDump(coll, "Hello");
    AddAndDump(coll, "My");
    AddAndDump(coll, "Name");
    AddAndDump(coll, "Is");
    AddAndDump(coll, "Pax");
  }
}

When you run that, you can see something like:

Adding [Hello]
   0: Hello
Adding [My]
   0: Hello
   1: My
Adding [Name]
   0: Hello
   1: My
   2: Name
Adding [Is]
   0: Hello
   1: Is
   2: My
   3: Name
Adding [Pax]
   0: Hello
   1: Pax
   2: Is
   3: My
   4: Name

indicating that, rightly so, order is not considered a salient feature of a set.

There are other ways to do it without a manual counter but it's a fair bit of work for dubious benefit.

2
  • 3
    This still seems to be the clearest solution, even with List and Iterable interfaces. Dec 17, 2013 at 17:14
  • 1
    100% it seems like after java8 anytime I put a forloop into a PR, everyone wants to remind me that there are a zillion alternatives. But this is readible, canonical and not susceptible to the problem in the first place Jun 3, 2022 at 20:52
31

Using lambdas and functional interfaces in Java 8 makes creating new loop abstractions possible. I can loop over a collection with the index and the collection size:

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

Which outputs:

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

Which I implemented as:

   @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());
      }
   }

The possibilities are endless. For example, I create an abstraction that uses a special function just for the first element:

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

Which prints a comma separated list correctly:

one,two,three,four

Which I implemented as:

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

Libraries will begin to pop up to do these sorts of things, or you can roll your own.

2
  • 10
    Not a criticism of the post (it's "the cool way to do it" these days I guess), but I struggle to see how this is easier/better than a simple old school for loop: for (int i = 0; i < list.size(); i++) { } Even grandma could understand this and it's probably easier to type without the syntax and uncommon characters a lambda uses. Don't get me wrong, I love using lambdas for certain things (callback/event handler type of pattern) but I just can't understand the use in cases like this. Great tool, but using it all the time, I just can't do.
    – Manius
    Feb 8, 2018 at 19:51
  • 1
    I suppose, some avoidance of off-by-one index over/underflows against the list itself. But there is the option posted above: int i = 0; for (String s : stringArray) { doSomethingWith(s, i); i++; }
    – Manius
    Feb 8, 2018 at 19:58
30

Java 8 introduced the Iterable#forEach() / Map#forEach() method, which is more efficient for many Collection / Map implementations compared to the "classical" for-each loop. However, also in this case an index is not provided. The trick here is to use AtomicInteger outside the lambda expression. Note: variables used within the lambda expression must be effectively final, that is why we cannot use an ordinary int.

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

I'm afraid this isn't possible with foreach. But I can suggest you a simple old-styled for-loops:

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

Notice that, the List interface gives you access to it.nextIndex().

(edit)

To your changed example:

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

Idiomatic Solution:

final Set<Double> doubles; // boilerplate
final Iterator<Double> iterator = doubles.iterator();
for (int ordinal = 0; iterator.hasNext(); ordinal++)
{
    System.out.printf("%d:%f",ordinal,iterator.next());
    System.out.println();
}

this is actually the solution that Google suggests in the Guava discussion on why they did not provide a CountingIterator.

13

Though there are soo many other ways mentioned to achieve the same, I will share my way for some unsatisfied users. I am using the Java 8 IntStream feature.

1. Arrays

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

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));
});
1
  • This is probably the closest to a solution that scala,ruby,python,javascript and other users can appreciate [speaking as one who uses all 5 languages) Nov 28, 2022 at 15:56
11

One of the changes Sun is considering for Java7 is to provide access to the inner Iterator in foreach loops. the syntax will be something like this (if this is accepted):

for (String str : list : it) {
  if (str.length() > 100) {
    it.remove();
  }
}

This is syntactic sugar, but apparently a lot of requests were made for this feature. But until it is approved, you'll have to count the iterations yourself, or use a regular for loop with an Iterator.

0
3

For situations where I only need the index occasionally, like in a catch clause, I will sometimes use 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);
  }
}
1
  • 3
    Be careful that this needs an .equals()-implementation of the Arrays objects which can identify a certain object uniquely. This is not the case for Strings, if a certain string is in the Array multiple times you will only get the index of the first occurence, even if you were already iterating on a later item with the same string.
    – Kosi2801
    Jun 16, 2017 at 8:55
2

If you need a counter in an for-each loop you have to count yourself. There is no built in counter as far as I know.

1
1

There is a "variant" to pax' answer... ;-)

int i = -1;
for(String s : stringArray) {
    doSomethingWith(s, ++i);
}
2
  • 3
    Curious, is there any benefit of using this over the, seemingly, clearer i=0; i++; approach? Dec 17, 2013 at 17:17
  • 1
    I guess if you need to use again the i index after doSomething in the for scope.
    – gcedo
    Jul 4, 2014 at 13:52
0

i usually use this workaround by using array

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
}
-1

The best and optimized solution is to do the following thing:

int i=0;

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

Where Type can be any data type and types is the variable on which you are applying for a loop.

2
  • Please provide your answer in a reproducible code format. Jan 4, 2020 at 21:19
  • This is exactly the way for which an alternative solution is wanted. The question is not about types but about possibilities to access the loop counter in a DIFFERENT way than counting manually.
    – Kosi2801
    Feb 16, 2020 at 18:03
-4

I'm a little surprised no-one suggested the following (I admit it's a lazy approach...); If stringArray is a List of some sort, you could use something like stringArray.indexOf(S) to return a value for the current count.

Note: this assumes that the elements of the List are unique, or that it doesn't matter if they are non-unique (because in that case it will return the index of the first copy found).

There are situations in which that would be sufficient...

1
  • 10
    With a performance approaching O(n²) for the whole loop it's very hard to imagine even a few situations where this would be superior to anything else. Sorry.
    – Kosi2801
    Mar 5, 2011 at 21:57
-5

Here is an example of how I did this. This gets the index at the for each loop. Hope this helps.

public class CheckForEachLoop {

    public static void main(String[] args) {

        String[] months = new String[] { "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST",
                "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" };
        for (String s : months) {
            if (s == months[2]) { // location where you can change
              doSomethingWith(s); // however many times s and months
                                  // doSomethingWith(s) will be completed and 
                                  // added together instead of counter
            }

        }
        System.out.println(s); 


    }
}
3
  • 2
    Sorry, this is not answering the question. It's not about accessing the content but about a counter how often the loop already has been iterated.
    – Kosi2801
    Apr 16, 2019 at 18:02
  • Question was to find out the current index in the loop in a for-each style loop.
    – rumman0786
    Jul 17, 2019 at 5:06
  • Atleast keep it here and rate up as it is a similar answer in my opinion. Thank you for explanations Kosl2801 and rumman0786
    – ashkanaral
    Oct 27, 2020 at 0:01

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.