Sub topic 3
Writing Your First Lambda Expressions
The previous chapter introduced the functional interface. A functional interface is an interface with exactly one abstract method. This chapter shows how to write a lambda expression, which is a short way to supply the code for that one method.
You will learn the three parts of every lambda, the two kinds of lambda body, and how to write parameters with or without their types. You will also see the syntax mistakes beginners make most often and how to fix them.
The Three Parts of a Lambda
A lambda expression is a block of code that you can store in a variable or pass to a method. It looks like a method with no name, no return type, and no public keyword.
Every lambda has three parts:
- Parameters. These are the inputs, written in parentheses, such as
(a, b). - The arrow. This is the symbol
->. It separates the inputs from the work. - The body. This is the code that runs. It can be a single expression or a block in curly braces.
Here is a full example. It uses the Calculator interface. Its one abstract method, apply, takes two int values and returns an int.
@FunctionalInterface
interface Calculator {
int apply(int a, int b);
}
public class CalculatorDemo {
public static void main(String[] args) {
Calculator add = (a, b) -> a + b; // expression body
Calculator multiply = (int a, int b) -> { // explicit types, block body
return a * b;
};
System.out.println(add.apply(2, 3)); // 5
System.out.println(multiply.apply(2, 3)); // 6
}
}Save this as CalculatorDemo.java, then compile and run it:
javac CalculatorDemo.java
java CalculatorDemoThe lambda (a, b) -> a + b becomes the code for apply. When you call add.apply(2, 3), Java sets a to 2 and b to 3, runs the body, and returns 5.
Expression Bodies and Block Bodies
The body is the part after the arrow. You can write it in two ways.
Expression bodies
An expression is a piece of code that produces a value, such as a + b or name.length(). When the body is one expression, you write it directly after the arrow. There are no braces, no return, and no semicolon inside the lambda.
Calculator add = (a, b) -> a + b;Java returns the value of the expression for you.
Block bodies
A block body is one or more statements inside curly braces { }. Use a block when you need more than one step. Inside a block, you must write return yourself if the method returns a value, and each statement ends with a semicolon.
Calculator safeDivide = (a, b) -> {
if (b == 0) {
return 0;
}
return a / b;
};The semicolon after the closing brace } ends the assignment statement. It is not part of the lambda.
Choosing between them
| Situation | Use | Example |
|---|---|---|
| One short calculation | Expression body | `(a, b) -> a + b` |
| Several steps, or an `if` | Block body | `(a, b) -> { if (b == 0) return 0; return a / b; }` |
| Method returns nothing (`void`) and you call one method | Expression body | `() -> System.out.println("Hi")` |
| Method returns nothing and you need several statements | Block body | `() -> { log(); save(); }` |
Writing Parameters
How you write the parameters depends on how many there are and whether you write their types.
Zero parameters
Use empty parentheses. Runnable is a built-in functional interface whose method, run, takes no inputs and returns nothing.
Runnable sayHi = () -> System.out.println("Hi");One parameter
With one parameter and no written type, the parentheses are optional. These two lines mean the same thing:
Greeter g1 = name -> "Hello, " + name;
Greeter g2 = (name) -> "Hello, " + name;Two or more parameters
Parentheses are required, and commas separate the names: (a, b) -> a + b.
Inferred and explicit types
Type inference means the compiler works out a type that you did not write. In (a, b) -> a + b, you never said that a and b are int. The compiler knows this because Calculator.apply takes two int values. The next chapter explains how this works in detail.
You may also write the types yourself. These are called explicit types:
Calculator multiply = (int a, int b) -> a * b;On Java 11 or later, you may also write var for each parameter, as in (var a, var b) -> a * b. Most code uses plain inferred names, because they are shorter.
Explicit types are useful in two cases. They help a reader who cannot easily see the interface. They are also required if you want to put an annotation such as final on a parameter: (final int a, final int b) -> a * b.
A Complete Practice Program
This program puts every form from this chapter into one file. Save it as LambdaForms.java.
@FunctionalInterface
interface Greeter {
String greet(String name);
}
@FunctionalInterface
interface Calculator {
int apply(int a, int b);
}
public class LambdaForms {
public static void main(String[] args) {
// Zero parameters, expression body
Runnable sayHi = () -> System.out.println("Hi");
// One parameter, no parentheses
Greeter friendly = name -> "Hello, " + name;
// One parameter, explicit type, block body
Greeter formal = (String name) -> {
String title = name.length() > 3 ? "Dr. " : "Mx. ";
return "Good day, " + title + name;
};
// Two parameters, inferred types
Calculator subtract = (a, b) -> a - b;
// Two parameters, block body with a check
Calculator safeDivide = (a, b) -> {
if (b == 0) {
return 0;
}
return a / b;
};
sayHi.run(); // Hi
System.out.println(friendly.greet("Ada")); // Hello, Ada
System.out.println(formal.greet("Grace")); // Good day, Dr. Grace
System.out.println(subtract.apply(10, 4)); // 6
System.out.println(safeDivide.apply(10, 0)); // 0
System.out.println(safeDivide.apply(10, 2)); // 5
}
}Run it with javac LambdaForms.java followed by java LambdaForms. Try changing one lambda at a time and see if it still compiles.
Common Syntax Mistakes
The compiler is strict about lambda syntax. These are the errors beginners hit most often.
| Mistake | Why it fails | Fix |
|---|---|---|
| `(a, b) -> return a + b;` | `return` is only allowed inside a block body | `(a, b) -> a + b` or `(a, b) -> { return a + b; }` |
| `(a, b) -> { a + b; }` | A block must use `return` to give back a value, and `a + b;` is not a valid statement on its own | `(a, b) -> { return a + b; }` |
| `a, b -> a + b` | Two or more parameters need parentheses | `(a, b) -> a + b` |
| `String name -> name.length()` | A parameter with a written type needs parentheses | `(String name) -> name.length()` |
| `(int a, b) -> a + b` | You cannot mix explicit and inferred types | `(int a, int b) -> a + b` or `(a, b) -> a + b` |
| `(a) -> a + 1` for `Calculator` | The number of parameters must match the interface method | `(a, b) -> a + b` |
| `(a, b) -> { return a + b }` | A statement inside the block is missing its semicolon | `(a, b) -> { return a + b; }` |
How Java Reads a Lambda
When the compiler sees a lambda, it checks a short list of rules:
- It finds the functional interface the lambda is assigned to, such as
Calculator. - It finds that interface's one abstract method, such as
int apply(int a, int b). - It checks that the lambda has the same number of parameters.
- It gives each inferred parameter the matching type from the method.
- It checks that the body returns the right type, or returns nothing for a
voidmethod.
If any rule fails, you get a compile error. This means mistakes show up before the program runs.
Exercise
Write a lambda for the Calculator interface that returns the larger of its two inputs. Write it once with a block body using an if statement, and once with an expression body.
Show answer
Block body: Calculator larger = (a, b) -> { if (a > b) { return a; } return b; }; Expression body: Calculator larger = (a, b) -> a > b ? a : b; Both are valid because Calculator.apply takes two ints and returns an int.
Exercise
Why does the line Calculator add = (a, b) -> { a + b; }; fail to compile, and what are two ways to fix it?
Show answer
A block body must use a return statement to give back a value, and a + b; is not a valid statement by itself. Fix it with an expression body, (a, b) -> a + b, or with a return inside the block, (a, b) -> { return a + b; }.
Exercise
Which of these lambdas are valid for the Greeter interface, whose method is String greet(String name)? (1) name -> "Hi " + name (2) String name -> "Hi " + name (3) (String n) -> "Hi " + n (4) () -> "Hi"
Show answer
Lambdas 1 and 3 are valid. Lambda 2 fails because a parameter with a written type needs parentheses. Lambda 4 fails because greet takes one parameter, and this lambda has none.