In Python, the enumerate
function allows you to iterate over a sequence of (index, value) pairs. For example:
JavaScript
x
8
1
>>> numbers = ["zero", "one", "two"]
2
>>> for i, s in enumerate(numbers):
3
print i, s
4
5
0 zero
6
1 one
7
2 two
8
Is there any way of doing this in Java?
Advertisement
Answer
For collections that implement the List
interface, you can call the listIterator()
method to get a ListIterator
. The iterator has (amongst others) two methods – nextIndex()
, to get the index; and next()
, to get the value (like other iterators).
So a Java equivalent of the Python above might be:
JavaScript
1
9
1
import java.util.ListIterator;
2
import java.util.List;
3
4
List<String> numbers = Arrays.asList("zero", "one", "two");
5
ListIterator<String> it = numbers.listIterator();
6
while (it.hasNext()) {
7
System.out.println(it.nextIndex() + " " + it.next());
8
}
9
which, like the Python, outputs:
JavaScript
1
4
1
0 zero
2
1 one
3
2 two
4