Sobes.tech
Junior — Middle

Can you explain what an anonymous function is in programming and how it is used?

sobes.tech AI

Answer from AI

An anonymous function is a function that has no name and is usually used where a small behavior needs to be defined quickly, such as passing a function as an argument or using lambda expressions.

In Java, anonymous functions appeared with the introduction of lambda expressions in Java 8. They allow writing concise code, especially when working with functional interfaces (e.g., Runnable, Comparator).

Example of using an anonymous function (lambda) in Java:

List<String> names = Arrays.asList("Anna", "Bob", "Charlie");
names.sort((a, b) -> a.compareToIgnoreCase(b));

Here, (a, b) -> a.compareToIgnoreCase(b) is an anonymous function that implements the Comparator<String> interface without creating a separate class.