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

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

    I think this should be the java functionality that resemble the python "enumerate" most, though it is quite complicated and inefficent. Basically, just map the list's indices to its elements, using ListIterator or Collector:

    List list = new LinkedList<>(Arrays.asList("one", "two", "three", "four"));
    Map enumeration = new Map<>();
    ListIterator iter = list.listIterator();
    while(iter.hasNext){
        map.put(iter.nextIndex(), iter.next());
    }
    

    or using lambda expression:

    Set enumeration = IntStream.range(0, list.size()).boxed.collect(Collectors.toMap(index -> index, index -> list.get(index)));
    

    then you can use it with an enhanced for loop:

    for (Map.Entry entry : enumeration.entrySet){
        System.out.println(entry.getKey() + "\t" + entry.getValue());
    }
    

提交回复
热议问题