Functional interfaces and lambdas: a first look
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Many interfaces describe just one action: apply a discount, check a mark, work out a fare. Java gives such interfaces a name and a very short way to implement them, the lambda. This lesson is a first look; lambdas get a full section later in the course.
One abstract method
A functional interface is an interface with exactly one abstract method, such as interface Discount { int apply(int price); }. It may also have default and static methods, because those already have a body.
A food app applies one discount rule to a price. Its Discount interface has a single abstract method, apply, plus two helper methods that already have bodies.
interface Discount { int apply(int price); // the one abstract method
default int applyTwice(int price) { // has a body: does not count return apply(apply(price)); }
static boolean isValid(int price) { // has a body: does not count return price > 0; }}An interface with two abstract methods is not functional. A class can still implement it in the usual way, as in Interfaces: a contract (opens in a new tab), but a lambda cannot.
@FunctionalInterface asks the compiler to check
Put @FunctionalInterface above the interface. Like @Override (opens in a new tab), it changes nothing in a correct program; it only asks javac to check that there is exactly one abstract method.
Example 1 · Mistake: a second abstract method
@FunctionalInterfaceinterface Discount { int apply(int price); String label();}
public class NotFunctionalDemo { public static void main(String[] args) { Discount d = price -> price - 50; System.out.println(d.apply(300)); }}NotFunctionalDemo.java:1: error: Unexpected @FunctionalInterface annotation
@FunctionalInterface
^
Discount is not a functional interface
multiple non-overriding abstract methods found in interface Discount
NotFunctionalDemo.java:9: error: incompatible types: Discount is not a functional interface
Discount d = price -> price - 50;
^
multiple non-overriding abstract methods found in interface Discount
2 errorsWhat this code does
- With two abstract methods, a single lambda cannot say which one it implements, so
Discountis no longer functional. - The annotation makes javac point at the interface itself. Fix: remove
label(), or give it a body withdefault.
Without the annotation, a second abstract method shows up only where a lambda is used. The annotation is optional, but a good habit for any interface meant for lambdas.
Anonymous classes
An anonymous class is a class with no name that is defined and used to create one object in a single new expression, as in new Discount() { ... }. It implements an interface or extends a class just once, where it is needed.
A Rs. 50 discount used in one place hardly needs its own named class. First the way you know, a named class; then the same rule as an anonymous class, written and created in one step.
Example 2 · A functional interface with a named class
@FunctionalInterfaceinterface Discount { int apply(int price);}
class FlatDiscount implements Discount { public int apply(int price) { return price - 50; }}
public class NamedClassDemo { public static void main(String[] args) { Discount d = new FlatDiscount(); System.out.println("Pizza: Rs. " + d.apply(300)); }}Pizza: Rs. 250
What this code does
Discounthas one abstract method, so it is a functional interface, and the annotation confirms it.- This is the way you already know: a class that implements the interface, then
new.
Example 3 · The same discount as an anonymous class
@FunctionalInterfaceinterface Discount { int apply(int price);}
public class AnonymousDemo { public static void main(String[] args) { Discount d = new Discount() { public int apply(int price) { return price - 50; } }; System.out.println("Pizza: Rs. " + d.apply(300)); }}Pizza: Rs. 250
What this code does
new Discount() { ... }defines a class with no name and creates one object of it, in one step. Note the;at the end.- It saves writing a separate class, but there is still a lot of typing for one line of real work.
Note the ; after the closing brace: the whole new Discount() { ... } is one expression. An anonymous class can implement an interface with several methods, and can have its own fields.
Lambda expressions
A lambda expression is a short way to implement a functional interface: the parameters, an arrow ->, and a body, as in price -> price - 50. Java takes the interface and the method from the variable or parameter type.
Even the anonymous class needs five lines for one line of real work. A functional interface has only one method to write, so Java lets you write just its parameter and its result.
Example 4 · The same discount as a lambda
@FunctionalInterfaceinterface Discount { int apply(int price);}
public class LambdaDemo { public static void main(String[] args) { Discount flat = price -> price - 50; Discount tenOff = price -> price * 90 / 100; System.out.println("Pizza: Rs. " + flat.apply(300)); System.out.println("Shoes: Rs. " + tenOff.apply(2000)); }}Pizza: Rs. 250 Shoes: Rs. 1800
What this code does
price -> price - 50is the wholeapplymethod:priceis the parameter, andprice - 50is the value it returns.- Java knows it is
applyofDiscountfrom the variable type. Each lambda is a separateDiscountobject.
Example 5 · Two parameters, no parameters and a block body
@FunctionalInterfaceinterface Calculator { int calc(int a, int b);}
@FunctionalInterfaceinterface Greeting { String message();}
public class ParamsDemo { public static void main(String[] args) { Calculator add = (a, b) -> a + b; Calculator share = (bill, friends) -> { if (friends == 0) { return bill; } return bill / friends; }; Greeting hello = () -> "Good morning, Kavya"; System.out.println(add.calc(12, 30)); System.out.println(share.calc(1200, 4)); System.out.println(share.calc(1200, 0)); System.out.println(hello.message()); }}42 300 1200 Good morning, Kavya
What this code does
calctakes twoints, so its lambdas list two parameters in brackets. The names are your choice:(a, b)or(bill, friends).shareneeds anif, so its body is a block in{ }: full statements ending in;, andreturngives the result.messagetakes nothing, so its lambda starts with empty brackets:() -> ....
How to read and write them:
- One parameter:
p -> p * 2. Two:(a, b) -> a + b. None:() -> "Hello". - A one-expression body returns its value: no
return, no;inside. - A block body
{ ... }holds full statements and needsreturn; leaving it out givesbad return type in lambda expression. - A wrong number of parameters gives
incompatible parameter types in lambda expression.
Passing a lambda to a method
A shop prints bills with different discount rules. If printBill takes a Discount parameter, each caller can pass its own rule as a lambda, right inside the call.
Example 6 · Passing a lambda to a method
@FunctionalInterfaceinterface Discount { int apply(int price);}
public class PassLambdaDemo { static void printBill(String item, int price, Discount d) { System.out.println(item + ": Rs. " + price + " -> Rs. " + d.apply(price)); }
public static void main(String[] args) { printBill("Bag", 1200, p -> p - 200); printBill("Book", 400, p -> p * 80 / 100); printBill("Pen", 20, p -> p); }}Bag: Rs. 1200 -> Rs. 1000 Book: Rs. 400 -> Rs. 320 Pen: Rs. 20 -> Rs. 20
What this code does
- The third parameter is a
Discount, so each lambda written in the call becomes theapplyfor that call. printBilldoes not know any discount rule. The caller passes the rule in, as a piece of behaviour.
printBill never knows any discount rule: the caller passes behaviour in as a parameter. Without lambdas, each rule would need its own class.
Next step
Check your understanding
12 quick questions