Strategy with lambdas and functional interfaces
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)After the last lesson, ShopLite has a dozen tiny classes that each hold one line of discount maths. Is there a shorter way to write a rule that is only one line long?
A one-method strategy interface is a functional interface
Functional interface is an interface with exactly one abstract method. Java accepts a lambda, such as amount -> amount * 10 / 100, wherever such an interface is expected.
DiscountStrategy with only int discount(int amount) has exactly one abstract method, so a lambda can stand in for a whole class. Below, Checkout is given lambdas.
Example 1 · The same Checkout, with lambda strategies
@FunctionalInterfaceinterface DiscountStrategy { int discount(int amount);}
class StudentDiscount implements DiscountStrategy { // a class still works too public int discount(int amount) { return Math.min(amount * 15 / 100, 300); }}
class Checkout { private DiscountStrategy discount = amount -> 0; // null object as a lambda
void setDiscount(DiscountStrategy discount) { this.discount = discount; }
int payable(int amount) { return amount - discount.discount(amount); }}
public class LambdaStrategyDemo { public static void main(String[] args) { Checkout checkout = new Checkout(); System.out.println("No coupon: Rs " + checkout.payable(1499));
checkout.setDiscount(amount -> amount * 10 / 100); System.out.println("FEST10: Rs " + checkout.payable(1499));
checkout.setDiscount(amount -> amount >= 999 ? 200 : 0); System.out.println("FLAT200: Rs " + checkout.payable(1499));
checkout.setDiscount(new StudentDiscount()); System.out.println("STUDENT: Rs " + checkout.payable(1499)); }}No coupon: Rs 1499 FEST10: Rs 1350 FLAT200: Rs 1299 STUDENT: Rs 1275
What this code does
- Each lambda is a complete
DiscountStrategy: Java matches its single input andintresult to the interface's one method. Checkoutdid not change from the previous lesson. Lambdas and classes are interchangeable because both implement the same interface.
The optional @FunctionalInterface annotation asks the compiler to check the rule. If someone later adds a second abstract method, the build fails at the interface instead of at every lambda. Default and static methods do not count, so helpers can still be added.
String name(). With two abstract methods, it cannot take lambdas; this lesson keeps only discount.Passing lambdas and method references as strategies
Method reference is a short way to point at an existing method, written ClassName::method, such as DiscountRules::student. Java uses it where a lambda with the same inputs and result would fit.
A lambda is the shortest strategy. A method reference points at a method you already have, and a factory method builds lambdas from settings.
Example 2 · Method references and lambda factories
@FunctionalInterfaceinterface DiscountStrategy { int discount(int amount);}
class DiscountRules { static int student(int amount) { return Math.min(amount * 15 / 100, 300); }
static DiscountStrategy percentOff(int percent) { return amount -> amount * percent / 100; }
static DiscountStrategy flatOff(int off, int minAmount) { return amount -> amount >= minAmount ? off : 0; }}
class LoyaltyAccount { private final int points;
LoyaltyAccount(int points) { this.points = points; }
int redeem(int amount) { return Math.min(points, amount / 10); }}
public class MethodRefDemo { public static void main(String[] args) { LoyaltyAccount riya = new LoyaltyAccount(120);
DiscountStrategy[] rules = { DiscountRules::student, // static method reference DiscountRules.percentOff(20), // factory-made lambda DiscountRules.flatOff(150, 1000), riya::redeem // instance method reference }; String[] labels = {"student", "20% off", "Rs 150 off", "Riya's points"}; for (int i = 0; i < rules.length; i++) { System.out.println(labels[i] + ": Rs " + rules[i].discount(1499) + " off on Rs 1499"); } }}student: Rs 224 off on Rs 1499 20% off: Rs 299 off on Rs 1499 Rs 150 off: Rs 150 off on Rs 1499 Riya's points: Rs 120 off on Rs 1499
What this code does
DiscountRules::studentfitsDiscountStrategybecause the method takes anintand returns anint.riya::redeemis bound to Riya's account, so it uses her 120 points.percentOff(20)returns a new lambda that rememberspercent. One factory method replaces a whole family ofPercentOffclasses.
An instance method works too: riya::redeem uses one particular account. A lambda is better for one-liners, a method reference for a rule that already has a name.
The lambda inside percentOff(20) captures percent. A captured variable must be effectively final, which means it is never changed after it is set; otherwise the code does not compile.
Find the bug
Spot the lambda bug
Each snippet has one wrong line. Tap it, then read the fix.
A lambda captures a changing variable.
Round 1 of 2Built-in strategy types: Function, BiFunction, Comparator
Comparator is a Java interface with one method, compare, that decides which of two values comes first. list.sort(comparator) keeps the sorting algorithm fixed and takes the ordering rule as a strategy.
Java ships ready-made strategy types, and Comparator is the best known. Below, Function and BiFunction build a price pipeline, and comparators sort products.
Example 3 · Function and BiFunction as ready-made strategies
import java.util.function.BiFunction;import java.util.function.Function;
public class BuiltInFunctionsDemo { public static void main(String[] args) { Function<Integer, Integer> fest = amount -> amount - amount * 10 / 100; Function<Integer, Integer> addGst = amount -> amount + amount * 18 / 100;
System.out.println("Coupon, then GST: Rs " + fest.andThen(addGst).apply(1499)); System.out.println("GST, then coupon: Rs " + fest.compose(addGst).apply(1499));
BiFunction<Integer, String, Integer> shipping = (amount, pincode) -> pincode.startsWith("4") ? (amount >= 499 ? 0 : 40) : 70; System.out.println("Pune, Rs 350: shipping Rs " + shipping.apply(350, "411001")); System.out.println("Pune, Rs 1499: shipping Rs " + shipping.apply(1499, "411001")); System.out.println("Kochi, Rs 1499: shipping Rs " + shipping.apply(1499, "682001")); }}Coupon, then GST: Rs 1593 GST, then coupon: Rs 1592 Pune, Rs 350: shipping Rs 40 Pune, Rs 1499: shipping Rs 0 Kochi, Rs 1499: shipping Rs 70
What this code does
andThenrunsfestfirst andaddGstsecond;composeruns them the other way round. The order changes the result by a rupee here because of whole-rupee rounding.BiFunction<Integer, String, Integer>is a strategy with two inputs (amount and pincode) and one result, with no new interface to write.
Example 4 · Comparator: sort strategies for a product list
import java.util.ArrayList;import java.util.Comparator;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;
record Product(String name, int price, double rating, int sold) {}
public class SortStrategyDemo { public static void main(String[] args) { List<Product> products = new ArrayList<>(List.of( new Product("Earbuds", 1499, 4.2, 830), new Product("Power bank", 999, 4.5, 830), new Product("Smart watch", 2999, 4.1, 410), new Product("Neckband", 1299, 4.5, 260)));
Map<String, Comparator<Product>> sorts = new LinkedHashMap<>(); sorts.put("Price: low to high", Comparator.comparingInt(Product::price)); sorts.put("Top rated", Comparator.comparingDouble(Product::rating).reversed() .thenComparing(Product::name)); sorts.put("Most popular", Comparator.comparingInt(Product::sold).reversed() .thenComparing(Product::price));
for (Map.Entry<String, Comparator<Product>> sort : sorts.entrySet()) { products.sort(sort.getValue()); List<String> names = new ArrayList<>(); for (Product p : products) { names.add(p.name()); } System.out.println(sort.getKey() + ": " + names); } }}Price: low to high: [Power bank, Neckband, Earbuds, Smart watch] Top rated: [Neckband, Power bank, Earbuds, Smart watch] Most popular: [Power bank, Earbuds, Smart watch, Neckband]
What this code does
List.sortis the context: the sorting algorithm never changes, and eachComparatoris a strategy for the order. The page's "Sort by" menu maps straight onto this map.thenComparingbreaks ties: Power bank and Neckband share a 4.5 rating, and Earbuds and Power bank both sold 830.
Function<T, R> turns one value into another, BiFunction<T, U, R> takes two inputs, and andThen joins two functions into a pipeline such as "apply the coupon, then add 18% GST".
"Price: low to high", "Top rated" and "Most popular" are three comparators for one sort call.
DiscountStrategy says more than Function<Integer, Integer>). Use the built-ins for small, local jobs.A Map registry instead of a switch
Map registry is a Map<String, DiscountStrategy> that stores each coupon code with its rule. A lookup replaces a long switch, and getOrDefault supplies a do-nothing rule for unknown codes.
A Map from coupon code to strategy replaces the switch. Below, getOrDefault gives unknown codes no discount, and an admin adds a coupon while the program runs.
Example 5 · A Map registry, and adding a coupon at runtime
import java.util.HashMap;import java.util.Map;import java.util.TreeSet;@FunctionalInterfaceinterface DiscountStrategy { int discount(int amount);}
class Coupons { private static final Map<String, DiscountStrategy> RULES = new HashMap<>(Map.of( "FEST10", amount -> amount * 10 / 100, "FLAT200", amount -> amount >= 999 ? 200 : 0, "STUDENT", amount -> Math.min(amount * 15 / 100, 300)));
static DiscountStrategy forCode(String code) { return RULES.getOrDefault(code.trim().toUpperCase(), amount -> 0); }
static void add(String code, DiscountStrategy rule) { RULES.put(code.trim().toUpperCase(), rule); }
static TreeSet<String> codes() { return new TreeSet<>(RULES.keySet()); }}
public class RegistryDemo { static void show(String code, int amount) { int off = Coupons.forCode(code).discount(amount); System.out.println(code + " on Rs " + amount + ": Rs " + off + " off"); }
public static void main(String[] args) { show("fest10", 1499); show("DIWALI25", 2999);
Coupons.add("diwali25", amount -> amount > 2000 ? amount * 25 / 100 : 0); // admin adds a coupon show("DIWALI25", 2999); System.out.println("Codes: " + Coupons.codes()); }}fest10 on Rs 1499: Rs 149 off DIWALI25 on Rs 2999: Rs 0 off DIWALI25 on Rs 2999: Rs 749 off Codes: [DIWALI25, FEST10, FLAT200, STUDENT]
What this code does
getOrDefaultwithamount -> 0replaces aswitchwith adefaultbranch. An unknown code simply gives no discount.- The admin added
diwali25in small letters, butaddandforCodeboth upper-case the key, so the lookup finds it.TreeSetprints the codes in sorted order.
A HashMap registry can change while the program runs, for example when an admin adds a festival coupon. Keep the map in one class and normalise keys (such as upper case) both when you add and when you look up.
Predict the output
Predict the lookup
Read the code, then pick what it prints.
A shopper types the code in lower case.
When a named class is clearer than a lambda
Lambdas suit short rules. A record suits a rule that needs a name, checks its settings or has several lines. Below, PercentOff is a record and SlabDiscount a class.
Example 6 · When a record beats a lambda
@FunctionalInterfaceinterface DiscountStrategy { int discount(int amount);}
record PercentOff(int percent) implements DiscountStrategy { PercentOff { // checks the setting once if (percent < 1 || percent > 90) { throw new IllegalArgumentException("percent must be 1-90, got " + percent); } }
public int discount(int amount) { return amount * percent / 100; }}
record SlabDiscount(int[] limits, int[] offs) implements DiscountStrategy { public int discount(int amount) { // too long for a readable lambda int best = 0; for (int i = 0; i < limits.length; i++) { if (amount >= limits[i]) { best = offs[i]; } } return best; }}
public class NamedStrategyDemo { static void apply(DiscountStrategy rule, int amount) { System.out.println("Applied " + rule + ": Rs " + (amount - rule.discount(amount))); }
public static void main(String[] args) { apply(new PercentOff(10), 1499);
DiscountStrategy slabs = new SlabDiscount(new int[] {1000, 2000, 5000}, new int[] {100, 250, 700}); System.out.println("Slab on Rs 2999: Rs " + slabs.discount(2999) + " off");
try { new PercentOff(150); } catch (IllegalArgumentException e) { System.out.println("Rejected: " + e.getMessage()); } }}Applied PercentOff[percent=10]: Rs 1350 Slab on Rs 2999: Rs 250 off Rejected: percent must be 1-90, got 150
What this code does
- The record prints as
PercentOff[percent=10], so the log says exactly which rule ran. Its compact constructor rejects a bad setting when the rule is created, not when a customer pays. SlabDiscounthas a loop and two arrays; as a lambda it would be hard to read and impossible to name. Both still implement the sameDiscountStrategy.
Printing a lambda shows a generated class name with Lambda and a number in it, which tells nobody which coupon was applied. A record prints as PercentOff[percent=10].
The two styles mix freely, because both implement the same interface: the registry can hold lambdas for simple coupons and classes for complex ones.
Next step
Check your understanding
12 quick questions