Skip to content
Advertisement

Is there a Java equivalent of Python’s ‘enumerate’ function?

In Python, the enumerate function allows you to iterate over a sequence of (index, value) pairs. For example:

JavaScript

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

which, like the Python, outputs:

JavaScript
Advertisement