Junior — Middle
Explain what the concept of anonymous functions (Lambda) is and how it is used in programming.
sobes.tech AI
Answer from AI
Anonymous functions (Lambda) are functions without a name that can be defined directly at the point of use. They allow writing compact and expressive code, especially when working with collections, event handlers, and functional interfaces.
In programming with Java (for example, for Android), lambda expressions are often used to pass behavior as a parameter:
// Example of using a lambda for sorting a list of strings by length
List<String> names = Arrays.asList("Anna", "Bob", "Christopher");
names.sort((a, b) -> a.length() - b.length());
Here, (a, b) -> a.length() - b.length() is an anonymous function that compares the lengths of strings. Lambdas make the code more readable and reduce boilerplate code.