<!DOCTYPE html><html><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  </head>
  <body>
    <blockquote type="cite" cite="mid:b42941fe-2855-4401-bfdd-031e5f9e25e7@oracle.com"><font size="4" face="monospace"> A more grounded approach would be
        something like:<br>
        <br>
            interface ListIndex<T> {<br>
                int index();<br>
                T element();<br>
            }<br>
        <br>
        and allow a ListIndex<T> to be used as the induction
        variable for an iteration:<br>
        <br>
            for (ListIndex<String> i : strings) { <br>
                ... i.element()  ... i.index()<br>
            }<br>
      </font></blockquote>
    <p>Note that you can already archive something similar with an
      utility method.<br>
    </p>
    <blockquote>
      <pre>record ListIndex<T>(int index, T element) {}

static <T> Iterable<ListIndex<T>> enumerate(T[] array) {
  return enumerate(Arrays.asList(array));
}

static <T> Iterable<ListIndex<T>> enumerate(Iterable<T> iterable) {
  return () -> new Iterator<>() {
    private final Iterator<T> iterator = iterable.iterator();
    private int nextIndex;

    @Override
    public boolean hasNext() {
      return iterator.hasNext();
    }

    @Override
    public ListIndex<T> next() {
      return new ListIndex<>(nextIndex++, iterator.next());
    }
  };
}
</pre>
    </blockquote>
    <p>The name of the method is based on <a href="https://docs.python.org/3/library/functions.html#enumerate">enumerate(…)
        in Python</a>. Here is how you may use the method:</p>
    <blockquote>
      <pre>String[] strings = getSomeStrings();
for (ListIndex<String> item : enumerate(strings)) {
  System.out.println(item.index() + ": " + item.element());
}
</pre>
    </blockquote>
    <p>Unfortunately, Record Patterns in enhanced <font face="monospace">for</font> loops have been removed by <a href="https://openjdk.org/jeps/440">JEP 440</a> in Java 21. With
      enabled preview features, you were able to write the following in
      Java 20:</p>
    <blockquote>
      <pre>String[] strings = getSomeStrings();
for (ListIndex(int index, String element) : enumerate(strings)) {
  System.out.println(index + ": " + element);
}
</pre>
    </blockquote>
    <p>Let's hope something similar will be re-introduced in the future.</p>
  </body>
</html>