Functional interfaces: mistakes and practice
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Most lambda bugs come from a handful of choices: the wrong interface, the wrong generic types, two steps joined in the wrong order, needless boxing, and a lambda that depends on a variable or a value that keeps changing. Each one has a short, reliable fix.
Mistake 1: the wrong interface
Pick the interface by the shape of the lambda, then by the method that will receive it. A yes/no rule is a Predicate, not a Function<T, Boolean>: removeIf will not even accept the Function.
Go for the most specific type that fits.
Example 1 · A validation rule set for a student registration form
import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.function.Function;import java.util.function.Predicate;
record Registration(String name, String email, String phone, int age, String password) {}
public class RegistrationRulesDemo { static boolean allDigits(String s) { for (char c : s.toCharArray()) { if (!Character.isDigit(c)) { return false; } } return true; }
public static void main(String[] args) { Predicate<String> blank = s -> s == null || s.trim().isEmpty(); Predicate<String> hasDigit = s -> { for (char c : s.toCharArray()) { if (Character.isDigit(c)) { return true; } } return false; };
Map<String, Predicate<Registration>> rules = new LinkedHashMap<>(); rules.put("name is required", r -> Predicate.not(blank).test(r.name())); rules.put("email needs @ and a dot after it", r -> r.email().indexOf('@') > 0 && r.email().lastIndexOf('.') > r.email().indexOf('@')); rules.put("phone must be 10 digits", r -> r.phone().length() == 10 && allDigits(r.phone())); rules.put("age must be 17 to 30", r -> r.age() >= 17 && r.age() <= 30); Predicate<String> longEnough = p -> p.length() >= 8; rules.put("password needs 8+ characters and a digit", r -> longEnough.and(hasDigit).test(r.password()));
Function<Registration, List<String>> validate = r -> { List<String> errors = new ArrayList<>(); rules.forEach((message, rule) -> { if (!rule.test(r)) { errors.add(message); } }); return errors; };
List<Registration> forms = List.of( new Registration("Kavya Rao", "kavya@mail.in", "9845012345", 19, "kavya2024"), new Registration(" ", "rohan.mail.in", "98450", 19, "secret"), new Registration("Arjun", "arjun@college", "98450123AB", 34, "arjun1234"));
for (Registration f : forms) { List<String> errors = validate.apply(f); System.out.println((f.name().isBlank() ? "(no name)" : f.name()) + ": " + (errors.isEmpty() ? "OK" : errors)); } }}Kavya Rao: OK (no name): [name is required, email needs @ and a dot after it, phone must be 10 digits, password needs 8+ characters and a digit] Arjun: [email needs @ and a dot after it, phone must be 10 digits, age must be 17 to 30]
What this code does
- Each rule is a small
Predicate<Registration>stored with its error message in aLinkedHashMap, so the rules run, and the errors print, in a fixed order. A new rule is one moreput. validateis aFunction<Registration, List<String>>that runs every rule withMap.forEach(aBiConsumer). Theerrorslist is created inside the lambda and only changed throughadd, so nothing breaks the effectively final rule.- Small pieces are reused and combined:
Predicate.not(blank), andlongEnough.and(hasDigit)for the password.
A same-type change for replaceAll must be a UnaryOperator, and a lambda that takes an input cannot be a Supplier. When the result type differs from the input type, an operator is wrong: an average of two Integer marks is a Double, so it is a BiFunction<Integer, Integer, Double>, not a BinaryOperator<Integer>.
The quick guide:
- Takes one, returns another type:
Function. Same type:UnaryOperator. - Takes one, yes or no:
Predicate. Takes one, returns nothing:Consumer. - Takes nothing:
Supplier. Takes two:BiFunction,BiPredicate,BiConsumer,BinaryOperator. - Plain numbers in big loops:
IntPredicate,IntUnaryOperator,ToIntFunctionand friends.
Mistake 2: wrong or missing generic types
In Function<T, R> the input comes first and the result second. Swapping them, Function<Integer, String> len = s -> s.length();, makes s an Integer, and the compiler reports "cannot find symbol".
Example 2 · Mistake: the generic types are swapped
import java.util.function.Function;
public class SwappedTypesDemo { public static void main(String[] args) { Function<Integer, String> nameLength = name -> name.length(); System.out.println(nameLength.apply("Kavya")); }}SwappedTypesDemo.java:5: error: cannot find symbol
Function<Integer, String> nameLength = name -> name.length();
^
symbol: method length()
location: variable name of type Integer
SwappedTypesDemo.java:6: error: incompatible types: String cannot be converted to Integer
System.out.println(nameLength.apply("Kavya"));
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
2 errorsWhat this code does
- In
Function<Integer, String>the input isInteger, sonameis anInteger, which has nolength()method. - The lambda takes a
Stringand returns its length, so the right type isFunction<String, Integer>, orToIntFunction<String>to avoid boxing the result.
Leaving the types out gives a raw type, so every value becomes Object. Writing Function<int, int> fails because type arguments must be classes.
Predicate<Integer> and IntPredicate are unrelated, so a variable of one cannot be passed where the other is expected. Declare the type the method needs, or adapt with x -> rule.test(x).
Mistake 3: joining steps in the wrong order
f.andThen(g) runs f first; f.compose(g) runs g first. When steps do not commute, such as "add a bonus" and "take 10% tax", the wrong one silently gives a wrong number, with no error.
Example 3 · Mistake: compose where andThen was meant
import java.util.function.Function;
public class SalaryOrderDemo { public static void main(String[] args) { Function<Integer, Integer> addBonus = pay -> pay + 5000; Function<Integer, Integer> deductTax = pay -> pay - pay / 10;
// the rule: add the bonus first, then take 10% tax on the total Function<Integer, Integer> wrong = addBonus.compose(deductTax); Function<Integer, Integer> right = addBonus.andThen(deductTax);
System.out.println("Wrong (compose): " + wrong.apply(40000)); System.out.println("Right (andThen): " + right.apply(40000)); }}Wrong (compose): 41000 Right (andThen): 40500
What this code does
addBonus.compose(deductTax)runsdeductTaxfirst: 40000 becomes 36000, then 41000. The bonus escaped tax, and nothing warned about it.addBonus.andThen(deductTax)follows the rule: 45000, then 40500. Checking one value by hand catches this bug at once.
A safe habit: use only andThen, so the code reads in the order it runs, and test the pipeline with one value you can work out by hand. The same rule applies to Consumer.andThen and your own chaining methods: the left one runs first.
Mistake 4: boxing and changing values
Boxed interfaces on large int data create objects for every value and can throw NullPointerException on a null Integer. On arrays and big loops, use the primitive interfaces.
Predicate<Integer> boxedPass = m -> m >= 40; // each int is boxed to an IntegerIntPredicate pass = m -> m >= 40; // works on int directly, no objectsInteger missing = null;boxedPass.test(missing); // NullPointerException: null cannot be unboxedA lambda may only use local variables that are effectively final. The workaround int[] count = {0} compiles, but every lambda then shares one changing value, so lambdas run later all see the last one. Copy the value into a new local per lambda, use a plain loop for totals, or keep real state in a field.
A Supplier is a recipe, not a stored value: each get() makes a new OTP, ID or list. When two places need the same value, call get() once and keep the result.
Example 4 · One program, the right interface for each job
import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.function.BinaryOperator;import java.util.function.Consumer;import java.util.function.IntPredicate;import java.util.function.Predicate;import java.util.function.Supplier;import java.util.function.ToIntFunction;import java.util.function.UnaryOperator;
public class RightInterfaceDemo { public static void main(String[] args) { List<String> names = new ArrayList<>(List.of(" kavya", "", "ROHAN ", "divya"));
Predicate<String> blank = s -> s.trim().isEmpty(); // yes/no rule names.removeIf(blank);
UnaryOperator<String> tidy = s -> s.trim().toLowerCase(); // same type in and out names.replaceAll(tidy);
Consumer<String> show = s -> System.out.println("- " + s); names.forEach(show);
ToIntFunction<String> length = s -> s.length(); System.out.println("First name length: " + length.applyAsInt(names.get(0)));
Map<Character, Integer> perLetter = new TreeMap<>(); BinaryOperator<Integer> add = (a, b) -> a + b; for (String n : names) { perLetter.merge(n.charAt(0), 1, add); } System.out.println(perLetter);
IntPredicate passMark = m -> m >= 35; int[] marks = {42, 18, 77}; int passed = 0; for (int m : marks) { if (passMark.test(m)) { passed++; } } System.out.println("Passed: " + passed);
Supplier<List<String>> newBatch = () -> new ArrayList<>(); // make on demand List<String> batch = newBatch.get(); batch.add("CS-A"); System.out.println("Batch: " + batch); }}- kavya
- rohan
- divya
First name length: 5
{d=1, k=1, r=1}
Passed: 2
Batch: [CS-A]What this code does
- Every lambda sits in the most specific interface for its job.
removeIfneeds aPredicate,replaceAllaUnaryOperator,forEachaConsumer.lengthtakes an object and gives anint,addcombines two values of one type, andpassMarkis a plainintrule. - The counter
passedis changed in a plain loop, not in a lambda, and the batch list is made once withget()and kept in a variable.
Module quiz
Questions from the whole module. Your first answer is your score.
Problems
Graded easy to hard, using everything from this module.
Try each one yourself first. Use the hint if you get stuck. Mark it as done when it works.
Exercise 1· Easy
Write Predicate<String> validEmail: true when the address has an @ that is not the first character, and a . somewhere after the @. Test kavya@mail.in, @mail.in and rohan@mail.
kavya@mail.in -> true @mail.in -> false rohan@mail -> false
Exercise 2· Easy
Mask phone numbers in a list with replaceAll and a UnaryOperator<String>: keep the first 5 digits and replace the last 5 with XXXXX. Numbers: 9845012345, 9123456789.
[98450XXXXX, 91234XXXXX]
Exercise 3· Medium
This program does not compile because two lambdas are in the wrong interface. Change only the two declared types (and imports) so it prints the expected output.
import java.util.ArrayList;import java.util.List;import java.util.function.Function;import java.util.function.Supplier;
public class WrongShapeFixDemo { public static void main(String[] args) { List<String> names = new ArrayList<>(List.of("Ira", " ", "Om", "")); Function<String, Boolean> blank = s -> s.trim().isEmpty(); names.removeIf(blank); System.out.println(names);
Supplier<Integer> nextSeat = seat -> seat + 1; System.out.println("After seat 41 comes " + nextSeat.get(41)); }}[Ira, Om] After seat 41 comes 42
Exercise 4· Medium
Fix the generic types in this program. Do not change the lambdas or the calls.
import java.util.function.BiFunction;import java.util.function.Function;
public class FixGenericsDemo { public static void main(String[] args) { Function<Integer, String> initial = name -> name.charAt(0); BiFunction<Integer, Integer> percent = (got, max) -> got * 100.0 / max; System.out.println("Initial: " + initial.apply("Meera")); System.out.println("Percent: " + percent.apply(42, 50)); }}Initial: M Percent: 84.0
Exercise 5· Medium
Electricity bill: first add a fixed charge of Rs. 120, then add 5% duty on the total. The code joins the steps in the wrong order. Fix the pipeline line, then print the bill for energy charges of 800 and 1500.
import java.util.function.Function;
public class ElectricityBillDemo { public static void main(String[] args) { Function<Integer, Integer> fixedCharge = amt -> amt + 120; Function<Integer, Integer> duty = amt -> amt + amt * 5 / 100; Function<Integer, Integer> bill = fixedCharge.compose(duty); System.out.println("800 -> " + bill.apply(800)); System.out.println("1500 -> " + bill.apply(1500)); }}800 -> 966 1500 -> 1701
Exercise 6· Medium
Rewrite this boxed code to use primitive interfaces: the rule should be an IntPredicate and the method should take an int[] and an IntPredicate. Print the same two counts for the step counts 4200, 11050, 8000, 12500, 950, 10000.
import java.util.List;import java.util.function.Predicate;
public class StepsBoxedDemo { static int countIf(List<Integer> values, Predicate<Integer> rule) { int count = 0; for (Integer v : values) { if (rule.test(v)) { count++; } } return count; }
public static void main(String[] args) { List<Integer> steps = List.of(4200, 11050, 8000, 12500, 950, 10000); Predicate<Integer> goalMet = s -> s >= 10000; System.out.println("Goal met: " + countIf(steps, goalMet) + " days"); System.out.println("Lazy days: " + countIf(steps, goalMet.negate()) + " days"); }}Goal met: 3 days Lazy days: 3 days
Exercise 7· Hard
Build a rule set for a college fest registration. Record FestEntry(String team, int members, String leaderPhone, String event). Rules, in this order: team name is not blank; 2 to 4 members; leader phone is 10 digits; event is one of coding, quiz, robotics. Store them in a LinkedHashMap<String, Predicate<FestEntry>>, write a Function<FestEntry, List<String>> that returns the failed messages, and print each entry as in the expected output. Entries: (Byte Club, 3, 9876543210, coding), (empty team name, 5, 98765, dance), (Quizards, 1, 9123456780, quiz).
Byte Club: registered (no name): rejected [team name is required, team needs 2 to 4 members, leader phone must be 10 digits, unknown event] Quizards: rejected [team needs 2 to 4 members]
Exercise 8· Hard
This ticket desk program has two bugs from this module. The ticket slips all show the last number, and the OTP that is checked is not the OTP that was sent. Fix both without removing the int[] counter or the Supplier.
import java.util.ArrayList;import java.util.List;import java.util.Random;import java.util.function.Supplier;
public class TicketBugsDemo { public static void main(String[] args) { int[] counter = {100}; List<Supplier<String>> slips = new ArrayList<>(); for (String item : List.of("Laptop", "Mouse", "Keyboard")) { counter[0]++; slips.add(() -> "Ticket " + counter[0] + ": " + item); } slips.forEach(s -> System.out.println(s.get()));
Random random = new Random(3); Supplier<Integer> otp = () -> 1000 + random.nextInt(9000); System.out.println("OTP sent: " + otp.get()); System.out.println("OTP checked: " + otp.get()); }}Ticket 101: Laptop Ticket 102: Mouse Ticket 103: Keyboard OTP sent: 1734 OTP checked: 1734
Interview questions
Questions interviewers ask on this topic.
What's next
You finished the preview of Functional Interfaces in Practice
Java Programming has 26 sections, 252 modules and 1949 lessons. An account opens every lesson and saves your progress.
Finish up
Mark complete & continue
Next: What is a method reference?