Back to course

Functional Programming in Java: Lambda Expressions

Java Mastery: From Zero to Professional Developer (50-Lesson Journey)

Lesson 48: Functional Programming in Java: Lambda Expressions

Java 8 introduced significant functional programming features, notably Lambda Expressions, which simplify coding by providing a concise way to represent anonymous functions.

1. What is a Lambda Expression?

It is a short block of code that takes parameters and returns a value. It essentially provides the implementation for a method defined by a functional interface.

Syntax: (parameter list) -> { function body }

2. Functional Interfaces

A functional interface is any interface that contains exactly one abstract method. Lambda expressions can only be used in contexts where they implement a functional interface.

java // Example of a Functional Interface (from java.util.function) @FunctionalInterface interface MyConverter<T, R> { R convert(T from); }

3. Lambda Syntax Examples

A. Standard Syntax (Multi-line)

java MyConverter<String, Integer> stringToInt = (String s) -> { return Integer.parseInt(s); }; int num = stringToInt.convert("500");

B. Simplified Syntax (Single expression)

If the body is a single expression, you can omit the curly braces, return keyword, and parameter types (type inference).

java // List sort using a traditional anonymous class: Collections.sort(list, new Comparator() { public int compare(String a, String b) { return a.compareTo(b); } });

// List sort using a Lambda Expression: Collections.sort(list, (a, b) -> a.compareTo(b));

4. Method References

A shorthand for a lambda expression that simply calls an existing method. They make the code even cleaner.

java // Lambda: list.forEach(item -> System.out.println(item));

// Equivalent Method Reference: list.forEach(System.out::println);