Module 27 of 30 · Java Programming — Core to Enterprise · Intermediate

Lambda Expressions & Functional Interfaces

Duration: 7 min

Lambda expressions are a concise way to represent anonymous functions in Java. They enable functional programming by allowing you to pass behavior as data. Functional interfaces define contracts with a single abstract method, making them perfect targets for lambda expressions.

Lambda Syntax and Functional Interfaces

A lambda expression has the syntax: (parameters) -> { body }. A functional interface is an interface with exactly one abstract method.

@FunctionalInterface
public interface Greeting {
    void greet(String name);
}

public class LambdaDemo {
    public static void main(String[] args) {
        // Lambda expression
        Greeting greeting = name -> System.out.println("Hello, " + name);
        greeting.greet("Alice");
        
        // Multi-line lambda
        Greeting formal = (name) -> {
            System.out.println("Good morning, " + name);
            System.out.println("Welcome!");
        };
        formal.greet("Bob");
    }
}
Hello, Alice
Good morning, Bob
Welcome!

Predicate, Function, Consumer, and Supplier

Java provides built-in functional interfaces in java.util.function for common operations.

import java.util.function.*;

public class BuiltInFunctionalInterfaces {
    public static void main(String[] args) {
        // Predicate: takes one argument, returns boolean
        Predicate<Integer> isEven = n -> n % 2 == 0;
        System.out.println("Is 4 even? " + isEven.test(4));
        
        // Function: takes one argument, returns a value
        Function<String, Integer> stringLength = s -> s.length();
        System.out.println("Length of 'Java': " + stringLength.apply("Java"));
        
        // Consumer: takes one argument, returns nothing
        Consumer<String> printer = s -> System.out.println("Printing: " + s);
        printer.accept("Hello");
        
        // Supplier: takes no arguments, returns a value
        Supplier<Double> randomNumber = () -> Math.random();
        System.out.println("Random: " + randomNumber.get());
    }
}
Is 4 even? true
Length of 'Java': 4
Printing: Hello
Random: 0.7234...

Method References

Method references provide a shorthand syntax for lambda expressions that call existing methods. They use the :: operator.

import java.util.*;

public class MethodReferences {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
        
        // Lambda expression
        names.forEach(name -> System.out.println(name));
        System.out.println("---");
        
        // Method reference to System.out.println
        names.forEach(System.out::println);
        System.out.println("---");
        
        // Method reference to String::toUpperCase
        names.stream()
             .map(String::toUpperCase)
             .forEach(System.out::println);
    }
}
Alice
Bob
Charlie
---
Alice
Bob
Charlie
---
ALICE
BOB
CHARLIE

Practical Examples with Collections

Lambda expressions are powerful when working with collections and streams.

import java.util.*;
import java.util.stream.*;

public class CollectionsWithLambda {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        
        // Filter even numbers
        List<Integer> evens = numbers.stream()
                                     .filter(n -> n % 2 == 0)
                                     .collect(Collectors.toList());
        System.out.println("Even numbers: " + evens);
        
        // Map to squares
        List<Integer> squares = numbers.stream()
                                       .map(n -> n * n)
                                       .collect(Collectors.toList());
        System.out.println("Squares: " + squares);
        
        // Sum all numbers
        int sum = numbers.stream()
                         .reduce(0, (a, b) -> a + b);
        System.out.println("Sum: " + sum);
    }
}
Even numbers: [2, 4, 6, 8, 10]
Squares: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Sum: 55

Sorting with Lambda Expressions

Lambda expressions simplify custom sorting logic.

import java.util.*;

public class SortingWithLambda {
    static class Person {
        String name;
        int age;
        Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
        public String toString() {
            return name + " (" + age + ")";
        }
    }
    
    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
            new Person("Alice", 30),
            new Person("Bob", 25),
            new Person("Charlie", 35)
        );
        
        // Sort by age
        people.sort((p1, p2) -> Integer.compare(p1.age, p2.age));
        System.out.println("Sorted by age: " + people);
    }
}
Sorted by age: [Bob (25), Alice (30), Charlie (35)]

❓ What is the syntax for a lambda expression with no parameters?

❓ Which functional interface takes one argument and returns a boolean?

❓ What does a method reference use to reference a method?

❓ What does the filter() method do in a stream?

❓ Which functional interface takes no arguments and returns a value?

Learn more: https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html

← Previous Continue interactively → Next →

Related Courses