Interview question
What is a lambda expression in Java and what problem does it solve? Java में lambda expression क्या है और यह कौन-सी problem solve करता है?
Answer
A lambda expression is a concise way to represent an anonymous function - a block of code that can be passed around as a value. It solves the verbosity of anonymous inner classes for simple, single-method implementations.
// BEFORE Java 8 - verbose anonymous inner class
Runnable oldWay = new Runnable() {
@Override
public void run() {
System.out.println('Running');
}
};
// WITH lambda (Java 8+) - concise
Runnable newWay = () -> System.out.println('Running');
// Lambda syntax variations
Comparator<Integer> comp1 = (a, b) -> a - b; // expression body
Comparator<Integer> comp2 = (a, b) -> { return a - b; }; // block body
Runnable r = () -> System.out.println('No parameters'); // no params
Function<Integer, Integer> square = x -> x * x; // single param, no parens needed
Function<Integer, Integer> square2 = (x) -> x * x; // parens optional here
// Using lambdas with Collections
List<String> names = new ArrayList<>(List.of('Charlie', 'Alice', 'Bob'));
// BEFORE - anonymous class for sorting
Collections.sort(names, new Comparator<String>() {
public int compare(String a, String b) {
return a.compareTo(b);
}
});
// WITH lambda
Collections.sort(names, (a, b) -> a.compareTo(b));
// Even shorter with method reference
Collections.sort(names, String::compareTo);Lambda expression एक anonymous function को concisely represent करने का तरीका है - code का ऐसा block जो value की तरह pass किया जा सकता है। यह simple, single-method implementations के लिए anonymous inner classes की verbosity solve करता है।
// Java 8 से पहले - verbose anonymous inner class
Runnable oldWay = new Runnable() {
@Override
public void run() {
System.out.println('Running');
}
};
// Lambda के साथ (Java 8+) - concise
Runnable newWay = () -> System.out.println('Running');
// Lambda syntax variations
Comparator<Integer> comp1 = (a, b) -> a - b;
Comparator<Integer> comp2 = (a, b) -> { return a - b; };
Runnable r = () -> System.out.println('कोई parameters नहीं');
Function<Integer, Integer> square = x -> x * x;
List<String> names = new ArrayList<>(List.of('Charlie', 'Alice', 'Bob'));
// पहले - anonymous class
Collections.sort(names, new Comparator<String>() {
public int compare(String a, String b) {
return a.compareTo(b);
}
});
// Lambda के साथ
Collections.sort(names, (a, b) -> a.compareTo(b));
// Method reference से और छोटा
Collections.sort(names, String::compareTo);Was this answer clear?