API reference

Package io.github.repeat: one class, one functional interface. Generated Javadoc for every version is on javadoc.io.

Summary

TypeMemberDescription
Repeatrepeat(int, IndexedAction<E>)Runs the action times times with the zero-based index.
IndexedAction<E>accept(int)The action your lambda implements; may throw E.

Repeat

final class since 1.0.0

Kotlin-style function for running code multiple times. Designed for static import. Holds only static members; it cannot be instantiated.

public final class Repeat

repeat

public static <E extends Throwable> void repeat(
        final int times,
        final IndexedAction<E> action) throws E

Executes the action the given number of times, passing the zero-based index of each iteration. Like Kotlin’s repeat, a zero or negative times runs nothing.

TYPE PARAMETERS
E — the exception type the action may throw; inferred from the lambda.
PARAMETERS
times — the number of times to execute the actionaction — the action to execute; receives the index
THROWS
E — if the action fails; remaining iterations are not executed

Behavior

WhenResult
times > 0Calls action.accept(i) for i = 0 … times - 1, in order, on the calling thread.
times <= 0Does nothing. The action is never called.
action throws at index kIndexes 0 … k ran. The exception propagates unchanged, not wrapped.
action == nullNullPointerException on the first iteration; nothing if times <= 0.

Examples

import static io.github.repeat.Repeat.*;

// method reference: collect the indexes 0, 1, 2
List<Integer> indexes = new ArrayList<>();
repeat(3, indexes::add);

// ignore the index
StringBuilder out = new StringBuilder();
repeat(2, i -> out.append("x"));   // "xx"

IndexedAction<E>

functional interface since 1.0.0

An action that receives the zero-based index of the current iteration. You rarely name it: a lambda or method reference passed to repeat becomes one.

@FunctionalInterface
public interface IndexedAction<E extends Throwable>
TYPE PARAMETERS
E — the exception type accept may throw. For a lambda that throws nothing checked, the compiler infers RuntimeException, so callers declare nothing.

accept

void accept(int index) throws E
PARAMETERS
index — zero-based index of the current iteration
THROWS
E — any exception the action raises

Ways to write one

FormExampleE is
Lambdai -> log.info("run " + i)RuntimeException
Method referenceindexes::addRuntimeException
Throwing lambdai -> Files.delete(paths[i])IOException
Stored in a variableIndexedAction<IOException> a = i -> ...;as declared

Edit this page on GitHub