STUDYECRAT Java :  Lambda Expression
    
    
      
      60s
    
  
          Java  Lambda Expression
        
        Prove your skills in this interactive quiz
Live Code
Run snippets directly
Timed
60s per question
Scored
Earn 3D badges
★ Java 8 Lambda Expressions: Key Interview Points
1. Basic Lambda Syntax
      Function<Integer, Integer> square = x -> x * x;
System.out.println(square.apply(4)); // Output: 16
// Single-parameter lambda with explicit type (Function)
    System.out.println(square.apply(4)); // Output: 16
// Single-parameter lambda with explicit type (Function)
- Tip: Use 
varfor cleaner syntax in Java 11+:var square = (Integer x) -> x * x; - Real Use: Simplifies anonymous class implementations (e.g., 
RunnableorComparator). 
2. Method References
      List<String> names = Arrays.asList("Alice", "Bob");
names.forEach(System.out::println);
// Equivalent to: names.forEach(s -> System.out.println(s));
    names.forEach(System.out::println);
// Equivalent to: names.forEach(s -> System.out.println(s));
- Tip: Prefer method references for readability when the lambda only calls an existing method.
 - Real Use: Used extensively in streams (e.g., 
map(String::toUpperCase)). 
3. Predicate Chaining
      Predicate<Integer> isEven = n -> n % 2 == 0;
Predicate<Integer> isPositive = n -> n > 0;
System.out.println(isEven.and(isPositive).test(10)); // Output: true
// Chains conditions with logical AND
    Predicate<Integer> isPositive = n -> n > 0;
System.out.println(isEven.and(isPositive).test(10)); // Output: true
// Chains conditions with logical AND
- Tip: Use 
negate()for inverse logic (e.g.,isEven.negate()). - Real Use: Filtering data in streams or conditional checks.
 
4. Lambda vs Anonymous Class
      Runnable lambda = () -> System.out.println("Lambda");
Runnable anonymous = new Runnable() {
public void run() { System.out.println("Anonymous"); }
};
// Lambdas reduce boilerplate for single-method interfaces
    Runnable anonymous = new Runnable() {
public void run() { System.out.println("Anonymous"); }
};
// Lambdas reduce boilerplate for single-method interfaces
- Tip: Lambdas can’t replace anonymous classes when needing multiple methods or state.
 - Real Use: Event listeners in Swing/AWT migrated from anonymous classes to lambdas.
 
5. Effectively Final Variables
      int offset = 10;
Function<Integer, Integer> adder = x -> x + offset;
// offset must be final or effectively final
// offset = 20; // Compilation error if uncommented
    Function<Integer, Integer> adder = x -> x + offset;
// offset must be final or effectively final
// offset = 20; // Compilation error if uncommented
- Tip: Use 
finalexplicitly for clarity in team projects. - Real Use: Capturing loop variables in lambdas (e.g., in stream operations).
 
💡 Pro Interview Tip
      When asked about lambdas, always mention functional interfaces (e.g., Predicate, Function) and their single abstract method (SAM) rule. This shows depth beyond syntax.
    

