0

Is there a way to use the augmented for loop to traverse through an array where the index is also required.

For example suppose I want to traverse an array of integers and add each number along with its index to a Map. My code will be something like

Map<Integer, Integer> map = new HashMap<>();
        for(int i=0; i< numbers.length; i++){
            map.put(numbers[i], i);
        }

Is there a way to write this using the for-each loop.

  • 1
    How is this question a duplicate of the one you've mentioned. I know how for-each loop works. The question is how can I access the index in a for-each loop? –  May 10 '16 at 23:33
  • 1
    In Java 8+ you could do `IntStream.of(0, numbers.length).forEach(i -> map.put(numbers[i], i));` – Elliott Frisch May 10 '16 at 23:33
  • @Clockwork I agree. Here's a better duplicate: http://stackoverflow.com/questions/3431529/java-how-do-i-get-current-index-key-in-for-each-loop – shmosel May 10 '16 at 23:58

0 Answers0