← Back to Home

Module 3: Java Lambda Expressions

Learning Objectives

Introduction to Lambda Expressions

This video introduces the concept of lambda expressions in Java and their relationship to functional programming concepts.

Understanding Functional Interfaces

A functional interface in Java is an interface that contains exactly one abstract method. Lambda expressions provide a way to implement these interfaces concisely.

Here's an example of a functional interface and its implementation using lambda expression:

// Functional interface definition
@FunctionalInterface
interface StringProcessor {
    String process(String input);
}

// Implementation using a lambda expression
StringProcessor reverser = (String s) -> {
    StringBuilder sb = new StringBuilder(s);
    return sb.reverse().toString();
};

// Usage
String result = reverser.process("Hello");  // Returns "olleH"

The key built-in functional interfaces in the java.util.function package include:

  • Function<T,R>: Takes a T argument and returns an R result. Method: R apply(T t)
  • Consumer<T>: Takes a T argument and returns no result. Method: void accept(T t)
  • Supplier<T>: Takes no arguments and returns a T result. Method: T get()
  • Predicate<T>: Takes a T argument and returns a boolean. Method: boolean test(T t)

Advanced Lambda Expressions

In this video, you'll learn advanced techniques for using lambda expressions with the Stream API and other functional programming patterns in Java.

Method References

Method references provide an even more concise way to express lambda expressions that simply call an existing method.

There are four types of method references:

// 1. Reference to a static method
Function<String, Integer> parser = Integer::parseInt;

// 2. Reference to an instance method of a particular object
String str = "Hello";
Supplier<Integer> lengthSupplier = str::length;

// 3. Reference to an instance method of an arbitrary object of a particular type
Function<String, Integer> lengthFunc = String::length;

// 4. Reference to a constructor
Supplier<List<String>> listSupplier = ArrayList::new;

Lambda Expressions with Streams

Java's Stream API works seamlessly with lambda expressions to process collections of objects:

List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "Dave");

// Filter names starting with 'A'
List<String> filteredNames = names.stream()
    .filter(name -> name.startsWith("A"))
    .collect(Collectors.toList());

// Transform names to uppercase
List<String> upperNames = names.stream()
    .map(String::toUpperCase)
    .collect(Collectors.toList());

// Find any name longer than 5 characters
Optional<String> longName = names.stream()
    .filter(name -> name.length() > 5)
    .findAny();

// Combine multiple operations
double averageLength = names.stream()
    .filter(name -> name.length() > 3)
    .mapToInt(String::length)
    .average()
    .orElse(0);

Key Topics

Resources