- Anonymous function (or Lambda) is a function without a reference variable.
- We use Lambdas when there is no need to store a reference to a function object, e.g. when passing a function as input parameter to a method or implementing a functional interface.
printer method which accepts a function
void printer(String input, Consumer<String> stringConsumer) {
stringConsumer.accept(input);
}
string to integer converter method
functional interface with name Converter
USAGE
passing an anonymous function as input parameter to printer method
Integer stringToIntegerConverter(String input, Converter<String, Integer> converter) {
return converter.convert(input);
}
functional interface with name Converter
@FunctionalInterface
interface Converter<F, T> {
T convert(F from);
}
USAGE
passing an anonymous function as input parameter to printer method
printer("Tom", i -> log.info("Hello " + i));
implementing a functional interface using anonymous function
log.info("stringToIntegerConverter output: " + stringToIntegerConverter("1", i -> Integer.valueOf(i)));
Comments
Post a comment