Java:Java Lambda Expressions and Functional Interfaces
Java•Lambdas & Scope

Java Lambda Expressions and Functional Interfaces

Lambda expressions provide concise anonymous implementations of Single Abstract Method (SAM) functional interfaces.

Syntax

(param1, param2) -> expression; list.filter(item -> condition);

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
->Lambda OperatorSeparates parameters from lambda body.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Java locally:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<String> frameworks = Arrays.asList("Spring", "Quarkus", "Micronaut", "Vert.x");

        // Filter and map using Java Streams and Lambdas
        List<String> filtered = frameworks.stream()
            .filter(f -> f.startsWith("M") || f.startsWith("S"))
            .map(String::toUpperCase)
            .collect(Collectors.toList());

        System.out.println("Original: " + frameworks);
        System.out.println("Filtered: " + filtered);
    }
}
Expected Output:
Original: [Spring, Quarkus, Micronaut, Vert.x]
Filtered: [SPRING, MICRONAUT]

How It Works: Step-by-Step

  • Lines 11-14: Applies stream filter with lambda predicate and method reference ::toUpperCase.
  • Line 14: collects results into a new List.

Key Concepts

  • Lambdas enable functional-style operations on collections.
  • Method references (String::toUpperCase) provide clean shorthand for single-method calls.
  • Streams do not mutate the underlying collection.

Common Mistake: Mutating local variables from inside a lambda expression

Variables referenced in a lambda must be effectively final; mutating them causes a compile error.

❌ Incorrect
int count = 0;
list.forEach(x -> count++); // Compile Error: local variables referenced from a lambda must be final
✅ Correct
// Use AtomicInteger or stream operations instead

Related Java Tutorials & Compiler

Run and test Java on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Java Online Compiler