The Functon interface in Java 8 represents an operation that accepts one argument and produces a result. This functional interface contains the abstarct method apply which defines the transformation logic.
@FunctionalInterface
public interface Transformer<T, R> {
R transform(T input);
default <V> Transformer<V, R> combineBefore(Transformer<? super V, ? extends T> preProcessor) {
Objects.requireNonNull(preProcessor);
return (V v) -> transform(preProcessor.transform(v));
}
default <V> Transformer<T, V> combineAfter(Transformer<? super R, ? extends V> postProcessor) {
Objects.requireNonNull(postProcessor);
return (T t) -> postProcessor.transform(transform(t));
}
static <T> Transformer<T, T> noChange() {
return t -> t;
}
}
Basic usage of the transformation operation:
Transformer<Integer, Integer> increment = x -> x + 10;
Integer output = increment.transform(10);
System.out.println(output); // Outputs 20
Method chaining example:
Transformer<Integer, Integer> scale = a -> a * 10;
Transformer<Integer, Integer> offset = a -> a + 10;
// First offset then scale
Transformer<Integer, Integer> combined1 = scale.combineBefore(offset);
System.out.println(combined1.transform(1)); // Outputs 110
// First scale then offset
Transformer<Integer, Integer> combined2 = scale.combineAfter(offset);
System.out.println(combined2.transform(1)); // Outputs 20
Practical validation implementation:
public class ValidationHelper {
private static final Transformer<String, String> sizeValidator = input -> {
if (input.length() > 100) {
throw new IllegalArgumentException("Input exceeds maximum length");
}
return input;
};
private static final Transformer<String, String> formatValidator = data -> {
if (!data.matches("^[a-fA-F0-9]+$")) {
throw new IllegalArgumentException("Invalid character pattern");
}
return data;
};
public static void validateInput(String value) {
formatValidator.combineBefore(sizeValidator).transform(value);
}
}