Logo

Programming-Idioms

History of Idiom 7 > diff from v156 to v157

Edit summary for version 157 by reilas:
[Java] edit

Version 156

2024-11-10, 06:30:44

Version 157

2024-11-12, 19:52:07

Idiom #7 Iterate over list indexes and values

Print each index i with its value x from an array-like collection items

Idiom #7 Iterate over list indexes and values

Print each index i with its value x from an array-like collection items

Variables
i,x,items
Variables
i,x,items
Extra Keywords
indices traverse traversal
Extra Keywords
indices traverse traversal
Imports
import java.util.stream.IntStream;
Imports
import static java.lang.System.out;
import static java.util.stream.IntStream.range;
Code
record E<T>(int i, T value) {}
@SuppressWarnings("unchecked")
<T> E<T>[] enumerate(T ... a) {
    return IntStream.range(0, a.length)
                    .mapToObj(i -> new E<>(i, a[i]))
                    .toArray(E[]::new);
}
Code
range(0, items.length).forEach(i -> {
    out.println(i + " = " + items[i]);
});
Doc URL
https://docs.oracle.com/en/java/javase/23/docs/api/java.base/java/util/stream/IntStream.html#range(int,int)