Auto indexing improved for() loops

Johannes Spangenberg johannes.spangenberg at hotmail.de
Wed Dec 6 23:46:14 UTC 2023


> A more grounded approach would be something like:
>
>     interface ListIndex<T> {
>         int index();
>         T element();
>     }
>
> and allow a ListIndex<T> to be used as the induction variable for an 
> iteration:
>
>     for (ListIndex<String> i : strings) {
>         ... i.element()  ... i.index()
>     }

Note that you can already archive something similar with an utility method.

    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());
         }
       };
    }

The name of the method is based on enumerate(…) in Python 
<https://docs.python.org/3/library/functions.html#enumerate>. Here is 
how you may use the method:

    String[] strings = getSomeStrings();
    for (ListIndex<String> item : enumerate(strings)) {
       System.out.println(item.index() + ": " + item.element());
    }

Unfortunately, Record Patterns in enhanced for loops have been removed 
by JEP 440 <https://openjdk.org/jeps/440> in Java 21. With enabled 
preview features, you were able to write the following in Java 20:

    String[] strings = getSomeStrings();
    for (ListIndex(int index, String element) : enumerate(strings)) {
       System.out.println(index + ": " + element);
    }

Let's hope something similar will be re-introduced in the future.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20231207/5639b4ec/attachment.htm>


More information about the amber-dev mailing list