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

前端 未结 11 586
别那么骄傲
别那么骄傲 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:11

    Strictly speaking, no, as the enumerate() function in Python returns a list of tuples, and tuples do not exist in Java.

    If however, all you're interested in is printing out an index and a value, then you can follow the suggestion from Richard Fearn & use nextIndex() and next() on an iterator.

    Note as well that enumerate() can be defined using the more general zip() function (using Python syntax):

    mylist = list("abcd")
    zip(range(len(mylist)), mylist)
    

    gives [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

    If you define your own Tuple class (see Using Pairs or 2-tuples in Java as a starting point), then you could certainly easily write your own zip() function in Java to make use of it (using the Tuple class defined in the link):

    public static  List> zip(List list_a, List list_b) {
        Iterator xiter = list_a.iterator();
        Iterator yiter = list_b.iterator();
    
        List> result = new LinkedList>();
    
        while (xiter.hasNext() && yiter.hasNext()) {
            result.add(new Tuple(xiter.next(), yiter.next()));
        }
    
        return result;
    }
    

    And once you have zip(), implementing enumerate() is trivial.

    Edit: slow day at work, so to finish it off:

    public static  List> enumerate (List list_in) {
        List nums = new ArrayList(list_in.size());
        for (int x = 0; x < list_in.size(); x++) { 
            nums.add(Integer.valueOf(x));
        }
    
        return zip (nums, list_in);
    }
    

    Edit 2: as pointed out in the comments to this question, this is not entirely equivalent. While it produces the same values as Python's enumerate, it doesn't do so in the same generative fashion that Python's enumerate does. Thus for large collections this approach could be quite prohibitive.

提交回复
热议问题