Java.Core.What are lambda expressions, and why are they used?

🌐 What are Lambda Expressions?

A lambda expression is a short, concise way to write anonymous functions (inline functions).
It allows you to pass behavior (code) as a method argument — instead of writing long-winded anonymous classes.


✅ Why were Lambdas introduced?

Lambdas were introduced in Java 8 (2014) to: ✔️ Make code more expressive and less verbose.
✔️ Enable functional programming style.
✔️ Make code working with collections and streams more elegant.
✔️ Simplify use of functional interfaces (like Comparator, Runnable, Function).


🔥 Example Before Lambdas — Anonymous Class

Old way (pre-Java 8):

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
Collections.sort(names, new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {
        return o1.compareTo(o2);
    }
});

✅ Works, but verbose.

🚀 Example With Lambda (Java 8+)

Collections.sort(names, (o1, o2) -> o1.compareTo(o2));

✅ Shorter, clearer, still works the same.

📜 Lambda Syntax

(parameters) -> { body }
PartMeaning
parametersInput to the lambda
->“Goes to” operator (lambda separator)
bodyCode to execute

✅ Examples of Lambdas

1️⃣ No Parameters

Runnable r = () -> System.out.println("Running");

2️⃣ Single Parameter (can skip parentheses)

Consumer<String> printer = s -> System.out.println(s);

3️⃣ Multiple Parameters

Comparator<String> comparator = (s1, s2) -> s1.compareTo(s2);

4️⃣ Multi-line Lambda

BiFunction<Integer, Integer, Integer> adder = (a, b) -> {
    System.out.println("Adding numbers");
    return a + b;
};

🔗 Where are Lambdas Used?

Streams API (map, filter, forEach)
Functional Interfaces (Runnable, Callable, Comparator, Predicate, etc.)
Event Handling (listeners)
Threading (tasks in Executors)


🔥 Example — Processing a List with Streams

List<String> names = List.of("Alice", "Bob", "Charlie");
names.stream()
     .filter(name -> name.startsWith("A"))
     .forEach(System.out::println);

✅ Functional, expressive, and concise.


📚 Lambda + Functional Interface

✅ In Java, lambdas work only with functional interfaces — interfaces with exactly one abstract method.

Example:

@FunctionalInterface
interface Printer {
    void print(String message);
}

Printer p = message -> System.out.println(message);

📊 Summary Table

FeatureLambda ExpressionAnonymous Class
VerbosityShortLong
SyntaxFunctionalOOP
Best forOne-off behaviorComplex, multi-method logic
Access to thisRefers to enclosing classRefers to anonymous class itself

🛠️ Key Benefits of Lambdas

✅ Less boilerplate — no need for full class declarations.
✅ More functional — behavior can be passed as a first-class object.
✅ Works great with Streams API and collections.
✅ Improves readability for simple logic.


⚠️ Limitations

  • Only works with functional interfaces (interfaces with 1 abstract method).
  • For complex behavior (lots of methods, large logic), use regular classes instead.

🎯 Final Pro Tip for Interviews

✅ Always say:

“Lambdas are concise inline functions, introduced in Java 8 to support functional programming and make working with functional interfaces and streams more expressive.”

✅ Mention:

  • Works with functional interfaces.
  • Used heavily in Streams API.
  • Reduces boilerplate anonymous class code.
This entry was posted in Без рубрики. Bookmark the permalink.