Java · Advanced level

Advanced level · Module 1: Generics, Lambdas and Streams · Lesson 2 of 4

Lambdas and Functional Interfaces

Pass behaviour as values with lambdas and method references, using the standard functional interfaces.

In this lesson you will

  • Write lambdas for Predicate, Function, Consumer and Supplier
  • Replace simple lambdas with method references

Key concepts

lambda expressionfunctional interfacePredicate / Function / Consumer / Suppliermethod reference

The lesson

A lambda is a short anonymous function: (a, b) -> a + b. It can be used wherever a functional interface — an interface with one abstract method — is expected. Comparator, Runnable and the java.util.function interfaces are all functional interfaces.

The standard interfaces cover most needs: Predicate<T> tests a value and returns boolean, Function<T, R> transforms a value, Consumer<T> uses a value, and Supplier<T> produces one. Predicates combine with and(), or() and negate().

When a lambda only calls an existing method, a method reference is clearer: s -> s.trim() becomes String::trim, and x -> System.out.println(x) becomes System.out::println. Lambdas can read local variables only if those variables are effectively final.

Step by step

  1. Write a Predicate<Sale> for sales above 10,000 SSP.
  2. Combine it with a second predicate using and().
  3. Write a Function<Sale, String> that formats a sale.
  4. Replace lambdas with method references where possible.

Practice activity

Write a filter utility that takes a list and a Predicate, then use it with five different lambdas on a list of products.

Expected result: One utility method serves every filter, and each filter is a one-line lambda or method reference.

Check your understanding

  1. What is a functional interface?

    Show answer

    An interface with exactly one abstract method, which a lambda can implement.

  2. Write a method reference equivalent to s -> s.toUpperCase().

    Show answer

    String::toUpperCase

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.