Skip to content
QuizMaker logoQuizMaker
Activity
Java Programming: From Zero to Enterprise
4. Advanced Java & Frameworks
1. Getting Started with Java & the JVM
2. Data Types & Variables
3. Control Flow: Ifs & Loops
4. String Manipulation in Depth
5. Methods (Functions) Architecture
6. Arrays & The Enhanced For Loop
7. User Input via Scanner
8. Mathematical Operations & The Math Class
9. Operators in Depth
10. Block Scope & Variable Lifecycles
11. Introduction to Object-Oriented Programming
12. Classes & Instances Deep Dive
13. Constructors
14. Encapsulation & The 'this' Keyword
15. Inheritance: Extending Functionality
16. Polymorphism & Method Overriding
17. Abstraction & Abstract Classes
18. Interfaces: The Ultimate Contract
19. Packages & Access Modifiers
20. Enums (Enumerations)
21. Exceptions: Handling Runtime Errors
22. The 'throw' and 'throws' keywords
23. Dates, Times, and Formatting
24. Enumerable Data Structures
25. LinkedLists: The Alternative
26. HashMaps: Key-Value Architecture
27. HashSets: The Art of Uniqueness
28. Iterator: Safe Collection Traversal
29. Wrapper Classes & Autoboxing
30. Basic File I/O
31. Generics: Type-Safe Templates
32. Lambda Expressions & Functional Interfaces
33. The Stream API: Functional Data Pipelines
34. Optional: Beating the NullPointerException
35. Multithreading & Concurrency Basics
36. JDBC: Connecting to SQL Databases
37. Annotations & Reflection
38. The JVM Garbage Collector
39. Introduction to Spring Boot
40. Unit Testing with JUnit
41. Java Collections for DSA
CONTENTS

32. Lambda Expressions & Functional Interfaces

Passing behavior as arguments elegantly without massive boilerplate classes.

Feb 22, 20263 views0 likes0 fires
18px

[!NOTE] Introduced in Java 8, Lambda Expressions fundamentally modernized the language. They allow you to pass specific "behavior" (a function) into another function, without having to build a massive, verbose Anonymous Inner Class.

The Boilerplate Problem

Imagine you have a Button object in a UI. You want to tell the button: "When you are clicked, execute this specific block of code."

Historically, you had to physically create a brand new class that implemented the ClickListener interface, write the overriding method, instantiate it, and pass it in.

// 2004 Java (Pre-Java 8)
button.setOnClickListener(new ClickListener() {
    @Override
    public void onClick() {
         System.out.println("Button clicked!");
    }
});

The Lambda Solution

A Lambda expression condenses all of that into a single, elegant arrow function: parameter -> expression.

If the interface only has one abstract method (called a Functional Interface), the Java compiler is smart enough to just inject your arrow function directly into that slot!

// Modern Java 8+ Implementation!
button.setOnClickListener( () -> System.out.println("Button Clicked!") );

Anatomy of a Lambda

Lambdas can take parameters and can have multi-line bodies wrapped in curly braces.

  1. No parameters:

() -> System.out.println("No args");

  1. One parameter (parentheses are optional!):

name -> System.out.println("Hello " + name);

  1. Multiple parameters with a multi-line body (requires { } and 'return'):

(x, y) -> {
    int sum = x + y;
    return sum;
}

Practical Use: Processing ArrayLists

Lambdas shine brightest when interacting with Collections.

import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList<Integer> numbers = new ArrayList<Integer>();
    numbers.add(5);
    numbers.add(9);
    numbers.add(8);
    numbers.add(1);
    
    // Instead of writing a complex Iterator while-loop...
    // We pass a Lambda function that tells '.forEach()' exactly what to do with each element 'n'!
    numbers.forEach( (n) -> { System.out.println(n); } );
  }
}

[!TIP] You cannot use a lambda expression if the target interface has two or more abstract methods. Lambdas ONLY work on Functional Interfaces (like Runnable, Callable, or Comparator) because otherwise the compiler wouldn't know which method you are trying to override!

Share this article

Share on TwitterShare on LinkedInShare on FacebookShare on WhatsAppShare on Email

Test your knowledge

Take a quick quiz based on this chapter.

mediumJava
Quiz: Lambdas
13 questions5 min

Continue Learning

33. The Stream API: Functional Data Pipelines

Advanced
14 min

34. Optional: Beating the NullPointerException

Advanced
10 min

35. Multithreading & Concurrency Basics

Advanced
14 min
Lesson 2 of 11 in 4. Advanced Java & Frameworks
Previous in 4. Advanced Java & Frameworks
31. Generics: Type-Safe Templates
Next in 4. Advanced Java & Frameworks
33. The Stream API: Functional Data Pipelines
← Back to Java Programming: From Zero to Enterprise
Back to Java Programming: From Zero to EnterpriseAll Categories