Logo

Programming-Idioms

History of Idiom 7 > diff from v153 to v154

Edit summary for version 154 by reilas:
[Java] typo

Version 153

2024-11-09, 02:28:33

Version 154

2024-11-09, 02:29:23

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) {
    @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);
}