In Python, the enumerate function allows you to iterate over a sequence of (index, value) pairs. For example:
>>> numbers = ["zero", "one", "two"]
>>> for i, s in enumerate(numbers):
... print i, s
...
0 zero
1 one
2 two
Is there any way of doing this in Java?
For collections that implement the
Listinterface, you can call thelistIterator()method to get aListIterator. The iterator has (amongst others) two methods –nextIndex(), to get the index; andnext(), to get the value (like other iterators).So a Java equivalent of the Python above might be:
which, like the Python, outputs: