Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

>>> 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?

like image 461
Richard Fearn Avatar asked Aug 23 '11 20:08

Richard Fearn


People also ask

What is the Java equivalent of a Python list?

Java has an interface called list, which has implementations such as ArrayList, AbstractList, AttributeList, etc. However, each one has different functionalities, and I don't know if they have everything you've specified such as . reverse().

What is Enumeration interface in Java?

The Enumeration interface defines the methods by which you can enumerate (obtain one at a time) the elements in a collection of objects. This legacy interface has been superceded by Iterator. Although not deprecated, Enumeration is considered obsolete for new code.

Is enumerate a function in Python?

What does enumerate do in Python? The enumerate function in Python converts a data collection object into an enumerate object. Enumerate returns an object that contains a counter as a key for each value within an object, making items within the collection easier to access.


1 Answers

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:

import java.util.ListIterator;   import java.util.List;  List<String> numbers = Arrays.asList("zero", "one", "two"); ListIterator<String> it = numbers.listIterator(); while (it.hasNext()) {     System.out.println(it.nextIndex() + " " + it.next()); } 

which, like the Python, outputs:

0 zero 1 one 2 two 
like image 114
Richard Fearn Avatar answered Oct 20 '22 00:10

Richard Fearn