A lambda expression packs a small piece of behaviour into a value, so one method can hand logic to another just as easily as it hands over a number. Before Java 8 this took a whole anonymous class; a lambda says the same thing in one line, such as s -> s.length() > 4. Lambdas are the basis of modern Java APIs, from sorting lists to the Streams API.
In this lesson you will learn
- Lambda syntax: parameters, arrow and body
- Functional interfaces and
@FunctionalInterface - Built-in interfaces:
Predicate,Function,Supplier,Consumer - Method references with
:: - Lambdas with collections: sorting,
forEachandremoveIf
Lambdas and Functional Interfaces
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
public class Main {
@FunctionalInterface
interface MathOp { int apply(int a, int b); }
public static void main(String[] args) {
MathOp add = (a, b) -> a + b;
MathOp power = (a, b) -> {
int r = 1;
for (int i = 0; i < b; i++) r *= a;
return r;
};
System.out.println(add.apply(3, 4) + " " + power.apply(2, 10));
Predicate<String> longWord = s -> s.length() > 4;
Function<String, Integer> len = String::length; // method reference
BiFunction<Integer, Integer, Integer> max = Math::max;
Supplier<List<String>> maker = ArrayList::new;
System.out.println(longWord.test("java") + " " + longWord.test("python"));
System.out.println(len.apply("lambda") + " " + max.apply(8, 3));
List<String> fresh = maker.get();
fresh.add("new list");
System.out.println(fresh);
Predicate<String> startsP = s -> s.startsWith("p");
System.out.println(longWord.and(startsP).test("python"));
}
}
Output
7 1024
false true
6 8
[new list]
true
- A lambda has parameters, an arrow
->and a body:(a, b) -> a + b. A single parameter needs no parentheses, and parameter types are usually inferred. - A one-expression body returns its value automatically. A body in braces needs an explicit
return, likepower. - A lambda’s type is a functional interface: an interface with exactly one abstract method.
MathOpis one;@FunctionalInterfaceasks the compiler to check this. java.util.functionprovides ready-made ones, so you rarely need to write your own.- A method reference such as
String::lengthorArrayList::newis shorthand for a lambda that just calls one existing method or constructor. - Many functional interfaces have helper methods;
longWord.and(startsP)combines two predicates.
| Interface | Method | Shape | Example |
|---|---|---|---|
Predicate<T> | test | T → boolean | n -> n > 0 |
Function<T,R> | apply | T → R | s -> s.length() |
Consumer<T> | accept | T → nothing | s -> System.out.println(s) |
Supplier<T> | get | nothing → T | () -> new ArrayList<>() |
BiFunction<T,U,R> | apply | T, U → R | (a, b) -> a * b |
Lambdas With Collections
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
record Student(String name, double cgpa) {}
public static void main(String[] args) {
List<Student> list = new ArrayList<>(List.of(
new Student("Tania", 3.95), new Student("Rafi", 2.98),
new Student("Mitu", 3.67), new Student("Arif", 3.41)));
list.sort(Comparator.comparingDouble(Student::cgpa).reversed());
list.forEach(s -> System.out.println(s.name() + " " + s.cgpa()));
list.sort(Comparator.comparing(Student::name));
System.out.println(list.get(0).name() + " is first by name");
list.removeIf(s -> s.cgpa() < 3.0);
System.out.println(list.size() + " left after removing CGPA below 3.0");
int bonus = 5; // effectively final: usable in a lambda
list.forEach(s -> System.out.println(s.name() + " +" + bonus));
}
}
Output
Tania 3.95
Mitu 3.67
Arif 3.41
Rafi 2.98
Arif is first by name
3 left after removing CGPA below 3.0
Arif +5
Mitu +5
Tania +5
Comparator.comparingDouble(Student::cgpa).reversed()builds a comparator that sorts by CGPA, highest first, with no hand-writtencomparemethod.forEachruns a lambda on every element;removeIfremoves those that match a predicate.- A lambda can use local variables from the surrounding method only if they are effectively final, meaning they are never reassigned.
bonusqualifies; changing it later would cause a compile error.
Common Mistakes
- Modifying a local variable inside a lambda, such as
count++; use anAtomicIntegeror a stream instead. - Writing long multi-line lambdas; move the logic into a named method and use a method reference.
- Forgetting
returnin a braced lambda body that must produce a value. - Expecting a lambda to work with an interface that has two abstract methods.
Practice Exercises
Exercise 1. Create a Function<Integer, Integer> that doubles a number, and another that adds 3. Combine them so 5 becomes 13.
Show answer
Function<Integer, Integer> doubleIt = n -> n * 2;
Function<Integer, Integer> addThree = n -> n + 3;
System.out.println(doubleIt.andThen(addThree).apply(5)); // 13
Exercise 2. Print every word in a list in upper case using forEach and a method reference.
Show answer
List<String> words = List.of("java", "lambda");
words.stream().map(String::toUpperCase).forEach(System.out::println);
Frequently Asked Questions
What is the difference between a lambda and an anonymous class?
Both create an object implementing an interface. A lambda is shorter, works only for functional interfaces, and its this refers to the enclosing object. An anonymous class can implement interfaces with several methods and has its own this.
Are lambdas slower than normal methods?
No meaningful difference for everyday code. The JVM creates lambdas efficiently and its just-in-time compiler optimises them like other method calls.
Summary
- A lambda is
(params) -> body, a compact way to pass behaviour. - Its target type is a functional interface with one abstract method.
- Predicate, Function, Consumer and Supplier cover most needs.
- Method references (
Class::method) shorten simple lambdas.
Next: Java Streams API.
