LearnFrenzy
Sign in Take a free test

Java Programming · Topic 21 of 28

Lambda Expressions

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Lambda Expressions · Study material

A lambda expression is a short block of code that you can pass around like a value: x -> x * x, (a, b) -> a + b, s -> s.isBlank(). Added in Java 8, lambdas brought functional programming to Java and replaced most anonymous classes: sorting a list, filtering it, reacting to an event or running a task now takes one readable line. A lambda always implements a functional interface – an interface with exactly one abstract method – and the JDK provides dozens of them in java.util.function (Predicate, Function, Consumer, Supplier and friends). Method references such as String::length and System.out::println shorten lambdas even further. This page covers the syntax, the standard functional interfaces, the four kinds of method reference, which variables a lambda may capture, how this differs from anonymous classes, composing functions, using lambdas with collections, and higher-order functions – the foundation for the Stream API in the next topic. Then practise with 60 questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – compiled and run on Java 21.

On this page

  • Lambda syntax and target typing
  • Functional interfaces and java.util.function
  • Method references: static, bound, unbound, constructor
  • Capturing effectively final variables
  • this in lambdas vs anonymous classes
  • Composing functions, collections and higher-order functions

Lambda syntax

FormExample
no parameters() -> System.out.println("hi")
one parameterx -> x * 2 or (x) -> x * 2
several parameters(a, b) -> a + b
explicit or var types(String a, String b) -> a.compareTo(b), (var a, var b) -> …
block bodyx -> { int y = x * x; return y + 1; }

A lambda has no type of its own: its type comes from the context it is used in (the target type), which must be a functional interface. The compiler infers the parameter types from that interface.

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;

public class Main {
    public static void main(String[] args) {
        // Before Java 8: an anonymous class just to pass one piece of behaviour
        Comparator<String> byLengthOld = new Comparator<String>() {
            @Override public int compare(String a, String b) { return a.length() - b.length(); }
        };

        // A lambda: (parameters) -> body
        Comparator<String> byLength = (a, b) -> a.length() - b.length();

        Runnable hello = () -> System.out.println("no parameters");                 // () for none
        Function<Integer, Integer> square = x -> x * x;                               // one parameter: parentheses optional
        BiFunction<Integer, Integer, Integer> add = (Integer a, Integer b) -> a + b;  // explicit types (optional)
        Function<String, String> shout = s -> {                                       // block body needs return
            String t = s.trim().toUpperCase();
            return t + "!";
        };
        Supplier<List<String>> listMaker = () -> new ArrayList<>();

        hello.run();
        List<String> words = listMaker.get();
        words.addAll(List.of("banana", "fig", "apple"));
        words.sort(byLength);
        System.out.println(square.apply(7) + " " + add.apply(3, 4) + " " + shout.apply("  hi ") + " " + words + " " + byLengthOld.compare("ab", "abc"));
    }
}

Output

no parameters
49 7 HI! [fig, apple, banana] -1

Functional interfaces

InterfaceMethodShapeTypical use
Predicate<T>testT → booleanfiltering, conditions
Function<T,R>applyT → Rtransforming
Consumer<T>acceptT → voidside effects (print, save)
Supplier<T>get() → Tfactories, lazy values
UnaryOperator<T>applyT → TreplaceAll
BinaryOperator<T>apply(T, T) → Treduce, merge
BiFunction<T,U,R>, BiConsumer, BiPredicateapply / accept / testtwo inputsmaps
IntPredicate, ToIntFunction, IntBinaryOperator …–primitive versionsavoid boxing
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.function.Consumer;
import java.util.function.Function;
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 Main {
    public static void main(String[] args) {
        Predicate<String> isEmail = s -> s.contains("@");             // T -> boolean        test
        Function<String, Integer> length = String::length;             // T -> R              apply
        Consumer<String> printer = s -> System.out.print("[" + s + "] ");   // T -> void      accept
        Supplier<Double> random = () -> 4.0;                            // () -> T             get
        UnaryOperator<String> trim = String::trim;                      // T -> T              apply
        BinaryOperator<Integer> max = Math::max;                        // (T, T) -> T         apply
        BiFunction<String, Integer, String> repeat = String::repeat;    // (T, U) -> R         apply
        IntPredicate even = n -> n % 2 == 0;                            // int -> boolean (no boxing)
        ToIntFunction<String> words = s -> s.split(" ").length;         // T -> int

        printer.accept("hello");
        System.out.println(isEmail.test("a@b.in") + " " + length.apply("lambda") + " " + random.get() + " " + trim.apply("  x  ") + " " + max.apply(3, 9));
        System.out.println(repeat.apply("ab", 3) + " " + even.test(10) + " " + words.applyAsInt("java is fun"));
    }
}

Output

[hello] true 6 4.0 x 9
ababab true 3

Method references

When a lambda only calls an existing method, a method reference says the same thing more briefly.

KindSyntaxEquivalent lambda
static methodInteger::parseInts -> Integer.parseInt(s)
method of a particular objectSystem.out::printlnx -> System.out.println(x)
method of an arbitrary objectString::toUpperCases -> s.toUpperCase()
constructorArrayList::new() -> new ArrayList<>()
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;

record Student(String name, int marks) {
    static boolean passed(Student s) { return s.marks() >= 40; }
}

public class Main {
    private final String prefix = ">> ";
    String decorate(String s) { return prefix + s; }

    public static void main(String[] args) {
        // 1. static method                ClassName::staticMethod
        Function<String, Integer> parse = Integer::parseInt;
        // 2. instance method of a particular object       object::method
        Main m = new Main();
        Function<String, String> deco = m::decorate;
        // 3. instance method of an arbitrary object of a type      ClassName::instanceMethod
        Function<String, String> upper = String::toUpperCase;          // s -> s.toUpperCase()
        BiFunction<String, String, Boolean> startsWith = String::startsWith;   // (s, p) -> s.startsWith(p)
        // 4. constructor                  ClassName::new
        Supplier<List<String>> newList = ArrayList::new;
        BiFunction<String, Integer, Student> makeStudent = Student::new;

        List<Student> list = new ArrayList<>(List.of(makeStudent.apply("Asha", 91), makeStudent.apply("Ravi", 35)));
        list.removeIf(s -> !Student.passed(s));
        List<String> names = newList.get();
        list.forEach(s -> names.add(s.name()));

        System.out.println(parse.apply("42") + 1);
        System.out.println(deco.apply("ok") + " " + upper.apply("java") + " " + startsWith.apply("lambda", "lam") + " " + names);
        names.forEach(System.out::println);                            // the most famous method reference
    }
}

Output

43
>> ok JAVA true [Asha]
Asha

Capturing variables

A lambda can read local variables of the enclosing method only if they are final or effectively final (never reassigned). It can freely read and modify fields. This rule avoids confusing behaviour and data races, because the lambda may run later or on another thread.

import java.util.ArrayList;
import java.util.List;
import java.util.function.IntSupplier;
import java.util.function.Supplier;

public class Main {
    private int fieldCounter = 0;                          // fields CAN be modified from a lambda

    void run() {
        String greeting = "Hi";                            // effectively final: never reassigned
        int base = 10;
        Supplier<String> s = () -> greeting + " there";    // capturing a local variable
        IntSupplier next = () -> base + ++fieldCounter;     // reading a local, changing a field
        // base++;                                         // ✘ would make 'base' not effectively final → compile error
        System.out.println(s.get() + " " + next.getAsInt() + " " + next.getAsInt() + " " + fieldCounter);

        int[] box = {0};                                    // workaround: mutate an object, not the variable
        List<String> log = new ArrayList<>();
        Runnable inc = () -> { box[0]++; log.add("inc"); };
        inc.run(); inc.run(); inc.run();
        System.out.println(box[0] + " " + log.size());

        List<Supplier<Integer>> suppliers = new ArrayList<>();
        for (int i = 1; i <= 3; i++) {
            int copy = i;                                   // each iteration has its own effectively final copy
            suppliers.add(() -> copy * 100);
        }
        suppliers.forEach(sup -> System.out.print(sup.get() + " "));
        System.out.println();
    }

    public static void main(String[] args) {
        new Main().run();
    }
}

Output

Hi there 11 12 2
3 3
100 200 300

this in lambdas vs anonymous classes

A lambda does not introduce a new scope: this means the enclosing object, and you cannot declare a variable with the same name as a local variable. An anonymous class is a real class with its own this and its own fields (state), and it can implement interfaces with several methods or extend abstract classes.

public class Main {
    private final String name = "Main object";

    @Override public String toString() { return name; }

    void demo() {
        Runnable lambda = () -> System.out.println("lambda this = " + this);       // this = the enclosing object
        Runnable anon = new Runnable() {
            @Override public void run() { System.out.println("anonymous this = " + this.getClass().getSimpleName().isEmpty() + ", outer = " + Main.this); }
        };
        lambda.run();
        anon.run();
        // An anonymous class creates a new class (Main$1.class) and a new scope with its own 'this';
        // a lambda is not a class and shares the enclosing scope.
        System.out.println(lambda.getClass().isAnonymousClass() + " " + anon.getClass().isAnonymousClass());
    }

    public static void main(String[] args) {
        new Main().demo();
    }
}

Output

lambda this = Main object
anonymous this = true, outer = Main object
false true

Composing functions

Functional interfaces have default methods for combining behaviour: Function.andThen and compose, Predicate.and, or and negate, and the Comparator.comparing … thenComparing … reversed family.

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;

record Product(String name, String category, int price) { }

public class Main {
    public static void main(String[] args) {
        Function<Integer, Integer> plusGst = p -> p * 118 / 100;
        Function<Integer, Integer> minus10 = p -> p - p / 10;
        System.out.println(plusGst.andThen(minus10).apply(1000) + " " + plusGst.compose(minus10).apply(1000) + " " + Function.<Integer>identity().apply(5));

        Predicate<String> longWord = s -> s.length() > 4;
        Predicate<String> startsJ = s -> s.startsWith("J");
        List<String> langs = List.of("Java", "JavaScript", "Python", "Go", "Julia");
        List<String> picked = new ArrayList<>();
        for (String l : langs) if (longWord.and(startsJ.negate()).or(String::isBlank).test(l)) picked.add(l);
        System.out.println(picked + " " + Predicate.not(startsJ).test("Go") + " " + Predicate.isEqual("Go").test("Go"));

        List<Product> ps = new ArrayList<>(List.of(new Product("Mouse", "IT", 699), new Product("Pen", "Office", 20), new Product("Keyboard", "IT", 1499), new Product("Desk", "Office", 7999)));
        ps.sort(Comparator.comparing(Product::category).thenComparing(Product::price, Comparator.reverseOrder()));
        ps.forEach(p -> System.out.print(p.name() + " "));
        System.out.println();
    }
}

Output

1062 1062 5
[Python] true true
Keyboard Mouse Desk Pen

Common mistakes

  • Modifying a captured local variable inside a lambda.
  • Using a lambda where the target is not a functional interface (e.g. Object).
  • Forgetting return in a block-body lambda, or adding one to a void lambda.
  • Reusing a local variable name as a lambda parameter.
  • Calling methods that throw checked exceptions inside Function/Consumer lambdas.
  • Long multi-line lambdas – extract them into named methods and use a method reference.
  • Boxing in hot code – use IntPredicate, IntFunction and similar primitive interfaces.

Key points to remember

  • A lambda implements a functional interface (one abstract method).
  • (params) -> expression, or (params) -> { statements; return …; }.
  • Predicate tests, Function transforms, Consumer acts, Supplier supplies.
  • Method references: Class::staticMethod, obj::method, Class::instanceMethod, Class::new.
  • Captured locals must be effectively final; fields may change.
  • In a lambda, this is the enclosing object.

Frequently asked questions

Is a lambda an object?

At run time it is an instance of a class generated by the JVM that implements the functional interface – but it is not an anonymous class and creates no .class file.

Can a lambda throw an exception?

Unchecked exceptions, yes. Checked ones only if the functional interface's method declares them (Callable does; Function does not).

Are lambdas slower than loops?

Usually not noticeably; the JIT optimises them well. Prefer clarity, and primitive specialisations for heavy numeric work.

Where can I learn more?

Read Java Lambda Expressions and Java Functional Interfaces, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About Java Programming

Java is one of the most used languages in the world – for enterprise software, Android apps, banking systems and backend services. This section covers core Java from syntax and data types to OOP, strings, arrays, exceptions, collections and multithreading, with clear explanations and practice questions for every topic.

Why it matters

  • Java is the main language in service-company placement tests and many product companies
  • OOP, String, collections and exception questions appear in nearly every Java interview
  • Strong core Java is the base for Spring Boot, Android and backend development
  • Java questions are common in university exams and certification tests

Who it is for

  • School students (Class 11–12 / ICSE computer applications) learning Java
  • College students (B.Tech, BCA, MCA) preparing for exams, labs and projects
  • Freshers preparing for placements, Java developer roles and technical interviews
  • Developers revising core Java before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Java developer interviews
  • Service company tests
  • University exams
  • Certification exams
  • Government IT exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links