Functional Interfaces, Lambdas and Method References
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Lambdas and method references are behind every stream, Optional and Comparator question, so interviewers test them early. They check that you can name the core interfaces, explain what a lambda really is, and say why a captured variable must be effectively final.
The core interfaces: Function, Predicate, Consumer, Supplier, BiFunction
Function<T, R> is the functional interface for a calculation: R apply(T t) takes one value and returns one result. Predicate tests a value, Consumer uses a value, and Supplier gives one.
Learn the core interfaces by their shape: what goes in and what comes out. Each line below uses one of them on a college fee.
Example 1 · Each core interface in one line
import java.util.function.BiFunction;import java.util.function.BinaryOperator;import java.util.function.Consumer;import java.util.function.Function;import java.util.function.Predicate;import java.util.function.Supplier;import java.util.function.UnaryOperator;
public class CoreInterfacesDemo { public static void main(String[] args) { Function<Integer, String> grade = m -> m >= 75 ? "Distinction" : "Pass"; Predicate<Integer> passed = m -> m >= 40; Consumer<String> notify = msg -> System.out.println("SMS: " + msg); Supplier<String> otp = () -> "482913"; BiFunction<Integer, Integer, Integer> total = (theory, lab) -> theory + lab; UnaryOperator<String> shout = s -> s.toUpperCase(); BinaryOperator<Integer> max = (a, b) -> a >= b ? a : b;
System.out.println("Function: " + grade.apply(82)); System.out.println("Predicate: " + passed.test(35)); notify.accept("Fees received"); System.out.println("Supplier: " + otp.get()); System.out.println("BiFunction: " + total.apply(62, 18)); System.out.println("UnaryOperator: " + shout.apply("result out")); System.out.println("BinaryOperator: " + max.apply(71, 88));
Predicate<Integer> distinction = m -> m >= 75; System.out.println("passed and not distinction (60): " + passed.and(distinction.negate()).test(60)); Function<Integer, Integer> addGrace = m -> m + 5; System.out.println("addGrace then grade (72): " + addGrace.andThen(grade).apply(72)); }}Function: Distinction Predicate: false SMS: Fees received Supplier: 482913 BiFunction: 80 UnaryOperator: RESULT OUT BinaryOperator: 88 passed and not distinction (60): true addGrace then grade (72): Distinction
What this code does
- Each variable's type says the shape:
applyforFunctionandBiFunction,testforPredicate,acceptforConsumer,getforSupplier. - The last two lines use default methods:
passed.and(distinction.negate())builds a new predicate, andaddGrace.andThen(grade)runsaddGracefirst, thengrade(72 + 5 = 77, a Distinction).
Model answer, spoken: "Function transforms, Predicate tests, Consumer consumes, Supplier supplies. They also have default methods to combine them: Predicate.and/or/negate, Function.andThen/compose, Consumer.andThen." Revise: java.util.function tour (opens in a new tab) and Composing functions (opens in a new tab).
Must know:
Function<T, R>:R apply(T t), one in, one out. Used bymap.Predicate<T>:boolean test(T t), a yes/no check. Used byfilter.Consumer<T>:void accept(T t), takes and returns nothing. Used byforEach.Supplier<T>:T get(), nothing in, one out. Used byorElseGet,generate.BiFunction<T, U, R>: two in, one out;BiConsumer,BiPredicatelikewise.UnaryOperator<T>is aFunction<T, T>;BinaryOperator<T>is aBiFunction<T, T, T>(used byreduce). Primitive versions:IntPredicate,ToIntFunction,IntBinaryOperatorand more.
Predict the output
Combine functions and predicates
Read each program and pick what it prints.
Round 1 of 4
f adds 2, g multiplies by 3. Run f first with andThen.
@FunctionalInterface rules
A functional interface is an interface with exactly one abstract method. Default methods, static methods and abstract methods that match public Object methods (such as equals) do not count.
Here is a custom FeeRule interface with a default and a static method. It still has one abstract method, so a lambda can implement it.
Example 2 · Your own @FunctionalInterface with default and static methods
@FunctionalInterfaceinterface FeeRule { int apply(int baseFee); // the single abstract method
default FeeRule then(FeeRule next) { // default methods are allowed return fee -> next.apply(apply(fee)); }
static FeeRule none() { // static methods are allowed return fee -> fee; }
String toString();}
public class CustomFunctionalDemo { public static void main(String[] args) { FeeRule hostelDiscount = fee -> fee - 5000; FeeRule lateFine = fee -> fee + 500;
System.out.println(hostelDiscount.apply(90000)); System.out.println(hostelDiscount.then(lateFine).apply(90000)); System.out.println(FeeRule.none().apply(90000)); }}85000 85500 90000
What this code does
FeeRulehas one abstract method,apply. Thedefaultmethodthen, thestaticmethodnoneand thetoString()declaration (anObjectmethod) do not break the rule.hostelDiscount.then(lateFine)returns a newFeeRulethat applies the discount and then the fine: 90000 - 5000 + 500 = 85500.
@FunctionalInterface is optional. It asks the compiler to check the rule, so adding a second abstract method later fails with Unexpected @FunctionalInterface annotation ... multiple non-overriding abstract methods found. Without the annotation the interface still works with lambdas as long as it has one abstract method. Revise: Custom functional interfaces (opens in a new tab).
Must know:
- One abstract method; any number of
defaultandstaticmethods. Comparatoris functional even though it declaresequals, because that matches a publicObjectmethod.Runnable,Callable,Comparator,ActionListenerare functional interfaces too.- An interface extending a functional interface stays functional only if it adds no new abstract method.
- A lambda's type comes from its target: the same lambda can be a
Predicateor your own interface.
Find the bug
Which line breaks the rule?
Each snippet should be a functional interface. Tap the wrong line, then check the fix.
A payment rule used with a lambda.
Round 1 of 3Four kinds of method references
A method reference is a short form of a lambda that only calls one existing method or constructor, written with ::. It has four kinds: static, bound object, arbitrary object of a type, and constructor.
A method reference replaces a lambda that only calls one method. Each of the four kinds below is shown with the lambda it replaces.
import java.util.List;
public class RefCompileSnip { public static void main(String[] args) { List<String> names = List.of("ravi", "asha", "meena"); names.stream() .map(String::toUpperCase) .sorted() .forEach(System.out::println); }}ASHA MEENA RAVI
Example 3 · All four kinds of method references
import java.util.ArrayList;import java.util.List;import java.util.function.BiFunction;import java.util.function.Function;import java.util.function.Supplier;
public class MethodRefDemo { record Student(String name) {}
public static void main(String[] args) { Function<String, Integer> parse = Integer::parseInt; // s -> Integer.parseInt(s) System.out.println("static: " + (parse.apply("42") + 8));
String college = "IIT "; Function<String, String> prefix = college::concat; // s -> college.concat(s) System.out.println("bound: " + prefix.apply("Madras"));
Function<String, String> upper = String::toUpperCase; // s -> s.toUpperCase() BiFunction<String, String, Boolean> same = String::equalsIgnoreCase; System.out.println("unbound: " + upper.apply("pune") + " " + same.apply("UPI", "upi"));
Supplier<List<String>> newList = ArrayList::new; Function<String, Student> makeStudent = Student::new; List<String> list = newList.get(); list.add("first"); System.out.println("constructor: " + list + " " + makeStudent.apply("Asha"));
List.of("x", "y").forEach(System.out::println); }}static: 50 bound: IIT Madras unbound: PUNE true constructor: [first] Student[name=Asha] x y
What this code does
- The comments show the lambda that each of the first three kinds replaces. In
String::toUpperCasethe object comes from the argument; incollege::concatthe object is fixed in advance. String::equalsIgnoreCasefits aBiFunctionbecause the first argument becomes the object and the second the parameter.Student::newpicks the record constructor that takes oneString.
Interviewers often ask you to name the four kinds with an example of each. Revise: Method reference basics (opens in a new tab) and unbound instance references (opens in a new tab).
The four kinds:
- Static method:
Integer::parseIntmeanss -> Integer.parseInt(s). - Instance method of a particular object:
System.out::println,college::concatmeanss -> college.concat(s). - Instance method of an arbitrary object of a type:
String::toUpperCasemeanss -> s.toUpperCase(); the first argument becomes the object. - Constructor:
ArrayList::newmeans() -> new ArrayList<>();Student::newmeansn -> new Student(n).
Fix the error
Fix the method reference
Read the real compiler error, then pick the line that fixes it.
Round 1 of 2
Create a student with no name.
Error
RefFix1.java:7: error: incompatible types: invalid constructor reference
Supplier<Student> make = Student::new;
^
constructor Student in record Student cannot be applied to given typesEffectively final variables in lambdas
A local variable is effectively final if it is assigned once and never changed afterwards, even without the final keyword. A lambda may use only effectively final local variables from its method.
A lambda can read a local variable only if it is never changed. Run this to see what compiles, and the clean fix.
Example 4 · Effectively final: what compiles and the clean fix
import java.util.List;import java.util.concurrent.atomic.AtomicInteger;
public class EffectivelyFinalDemo { public static void main(String[] args) { List<Integer> marks = List.of(72, 35, 88, 41); int passMark = 40; marks.stream().filter(m -> m >= passMark).forEach(m -> System.out.print(m + " ")); System.out.println();
// int count = 0; // marks.forEach(m -> count++); // compile error: count is changed
AtomicInteger count = new AtomicInteger(); marks.forEach(m -> { if (m >= passMark) { count.incrementAndGet(); } }); System.out.println("Passed (AtomicInteger): " + count.get());
long better = marks.stream().filter(m -> m >= passMark).count(); System.out.println("Passed (count()): " + better); }}72 88 41 Passed (AtomicInteger): 3 Passed (count()): 3
What this code does
passMarkis never reassigned, so the lambda may use it withoutfinal. Uncommentingcount++gives the compile errorlocal variables referenced from a lambda expression must be final or effectively final.AtomicIntegerworks because the variablecountalways points to the same object; only its contents change.count()on the stream gives the same answer with no shared state at all.
The lambda gets a copy of the value and may run later or on another thread, so a changing variable would be confusing and unsafe. Fields and array elements can be changed (only the local variable itself is restricted), which is why int[] count = {0} or an AtomicInteger compile. The cleaner fix is usually a stream result such as count() or sum(). Revise: Effectively final in lambdas (opens in a new tab).
Fix the error
Fix the captured variable
Read the real compiler error, then pick the line that fixes it.
Round 1 of 2
Add up the marks.
Error
SumFix.java:7: error: local variables referenced from a lambda expression must be final or effectively final
marks.forEach(m -> total += m);
^Lambda vs anonymous class: this and scope
A lambda shares the scope of the enclosing method and its this is the enclosing object. An anonymous class has its own scope, and its this is the anonymous object itself.
Print this from a lambda and from an anonymous class. The output shows who this is in each.
Example 5 · Predict the output: this in a lambda vs an anonymous class
public class ThisScopeDemo { private final String name = "outer ThisScopeDemo";
void run() { Runnable anonymous = new Runnable() { private final String name = "anonymous Runnable";
@Override public void run() { System.out.println("anonymous class this.name = " + this.name); } }; Runnable lambda = () -> System.out.println("lambda this.name = " + this.name);
anonymous.run(); lambda.run(); System.out.println("anonymous is a separate class: " + anonymous.getClass().isAnonymousClass()); }
public static void main(String[] args) { new ThisScopeDemo().run(); }}anonymous class this.name = anonymous Runnable lambda this.name = outer ThisScopeDemo anonymous is a separate class: true
What this code does
- In the anonymous class,
thisis theRunnableobject, sothis.namefinds its own field. In the lambda,thisis the enclosingThisScopeDemoobject. isAnonymousClass()is true for the anonymous object: it is a real class compiled to its own file, while a lambda is not an anonymous class.
Both may read only effectively final local variables. An anonymous class can implement an interface with many methods or extend a class; a lambda only fits a functional interface. Revise: Lambda or method reference (opens in a new tab).
Must know:
- An anonymous class compiles to its own
.classfile (Outer$1.class); a lambda is created at runtime. - An anonymous class can have fields and state; a lambda cannot.
- In a lambda, declaring a variable with the name of an existing local is a compile error; in an anonymous class it shadows the outer one.
Next step
Check your understanding
12 quick questions