Previous: Introduction to Advanced Java Next: Stream API and Collections

Module 2: Lambda Expressions and Functional Interfaces

Learning Objectives

2.1 Introduction to Lambda Expressions

What are Lambda Expressions?

Lambda expressions are anonymous functions that can be used to create delegates or expression tree types. They provide a concise way to represent one method interface using an expression.

Basic Syntax

// Basic lambda syntax
(parameters) -> expression
(parameters) -> { statements; }

// Examples
() -> System.out.println("Hello World")
(x) -> x * 2
(x, y) -> x + y
(String s) -> s.length()

Lambda in Test Automation

Lambda expressions can significantly simplify test code, especially when working with collections, event handling, and asynchronous operations.

// Traditional approach
@Test
public void testUserFiltering() {
    List<User> users = getUserList();
    List<User> activeUsers = new ArrayList<>();
    
    for (User user : users) {
        if (user.isActive()) {
            activeUsers.add(user);
        }
    }
    
    assertEquals(5, activeUsers.size());
}

// Lambda approach
@Test
public void testUserFiltering() {
    List<User> users = getUserList();
    
    long activeUserCount = users.stream()
        .filter(User::isActive)
        .count();
    
    assertEquals(5, activeUserCount);
}

2.2 Functional Interfaces

Built-in Functional Interfaces

Java 8 provides several built-in functional interfaces in the java.util.function package:

// Predicate example
Predicate<User> isActive = user -> user.isActive();
Predicate<User> isAdmin = user -> "admin".equals(user.getRole());

// Function example
Function<User, String> getUserEmail = user -> user.getEmail();

// Consumer example
Consumer<User> printUser = user -> System.out.println(user.getName());

// Supplier example
Supplier<User> createTestUser = () -> new User("test", "test@example.com");

2.3 Practical Examples

Test Data Validation

@Test
public void testUserValidation() {
    List<User> users = getUserList();
    
    // Check if all users have valid emails
    boolean allValidEmails = users.stream()
        .allMatch(user -> user.getEmail().contains("@"));
    
    assertTrue("All users should have valid emails", allValidEmails);
    
    // Check if any user is admin
    boolean hasAdmin = users.stream()
        .anyMatch(user -> "admin".equals(user.getRole()));
    
    assertTrue("Should have at least one admin", hasAdmin);
}
Previous: Introduction to Advanced Java Next: Stream API and Collections