Logo

Programming-Idioms

History of Idiom 7 > diff from v154 to v155

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

Version 154

2024-11-09, 02:29:23

Version 155

2024-11-10, 06:30:01

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 java.util.stream.IntStream;
Code
record E<T>(int i, T t) {
    @Override
    public String toString() {
        return "(%s, %s)".formatted(i, t);
    }
}
@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
record E<T>(int i, T t) {}
@SuppressWarnings("unchecked")
<T> E<T>[] enumerate(T ... a) {
    return IntStream.range(0, a.length)
                    .mapToObj(i -> new E<>(i, a[i]))
                    .toArray(E[]::new);
}