Is there a Java equivalent of Python's 'enumerate' function?

前端 未结 11 585
别那么骄傲
别那么骄傲 2020-12-08 01:59

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

>>> numbers = [\"zero\", \"one\", \"tw         


        
11条回答
  •  时光取名叫无心
    2020-12-08 02:14

    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:

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

    which, like the Python, outputs:

    0 zero
    1 one
    2 two
    

提交回复
热议问题