private static <T, X extends Throwable> void ifSet(T value, CheckedConsumer<? super T, ? extends X> operation) throws X { if (value != null) operation.accept(value); }
/** * Coerces a given {@link CheckedConsumer} into an equivalent {@link CheckedFunction} returning {@link Void}, * allowing the consumer to be used where a function is expected, and where the return value is irrelevant. * * @param <U> The input type. * @param <X> The exception type. * @param consumer The consumer. * @return The {@link Void}-returning {@link Function}. */ public static <U, X extends Throwable> CheckedFunction<U, Void, X> voidFunction(CheckedConsumer<? super U, ? extends X> consumer) { return u -> { consumer.accept(u); return null; }; } }
/** * Submits each element of the given collection to a checked consumer. An exception (if any) * thrown within the consumer is propagated to the caller. * * @param <T> Element type. * @param <X> Exception type. * @param collection The collection to traverse. * @param consumer The consumer. * @throws X If an exception occurs. */ public static <T, X extends Throwable> void forEach(Collection<? extends T> collection, CheckedConsumer<? super T, ? extends X> consumer) throws X { for (T element : collection) { consumer.accept(element); } }
/** * Chains the output of a function into the input of a consumer, thereby creating a new * consumer. * * @param <U> Input type of the {@code before} function. * @param <V> Output type of the {@code before} function and input type of the {@code after} consumer. * @param <X> Exception type. * @param before The initial function to apply. * @param after The consumer to chain to. * @return A composite {@link CheckedConsumer}. * @throws X If an error occurs. */ public static <U, V, X extends Throwable> CheckedConsumer<U, X> chain(CheckedFunction<U, V, X> before, CheckedConsumer<V, X> after) throws X { return u -> after.accept(before.apply(u)); }