Java 8 and beyond · 1. Java 8: lambdas and streams, lesson 1 of 4

Lambdas and functional interfaces

Intermediate5 min read@since 9Code runs on your Java 25
Explain it forThe essentials plus production detail and pitfalls.

A lambda is a short anonymous function: (params) -> expression. It implements a functional interface, meaning an interface with exactly one abstract method.

Built-in functional interfaces in java.util.function:

  • Predicate<T>: takes T, returns boolean (filtering)
  • Function<T, R>: takes T, returns R (transforming)
  • Consumer<T>: takes T, returns nothing (printing, saving)
  • Supplier<T>: takes nothing, returns T (creating)
  • plus BiFunction, UnaryOperator and BinaryOperator

Method references are shorthand when a lambda just calls one method: String::length, System.out::println, User::new.

A lambda can use local variables only if they are effectively final.

Lambda syntax

A lambda is a short anonymous function: parameters, an arrow, then an expression or a block. Parameter types are usually inferred from where the lambda is used.

Java
Runnable hello = () -> System.out.println("Hi");                        // no parameters
Function<Integer, Integer> square = x -> x * x;                         // one parameter: no brackets needed
Comparator<String> byLength = (a, b) -> Integer.compare(a.length(), b.length());   // two parameters
BinaryOperator<Integer> add = (a, b) -> {                               // a block needs return
    int sum = a + b;
    return sum;
};

Functional interfaces

A lambda needs a target type: an interface with exactly one abstract method (default and static methods don't count). @FunctionalInterface makes the compiler check that. java.util.function has ready-made ones, so you rarely write your own:

  • Predicate<T>: T → boolean (test)
  • Consumer<T>: T → nothing (accept)
  • Supplier<T>: nothing → T (get)
  • Function<T, R>: T → R (apply)
  • BiFunction<T, U, R>: (T, U) → R, plus BiConsumer and BiPredicate
  • UnaryOperator<T> and BinaryOperator<T>: same type in and out
  • Primitive versions such as IntPredicate, ToIntFunction and IntBinaryOperator avoid boxing.

The next subtopics show each of the main ones doing real work.

Java
@FunctionalInterface
interface DiscountRule {
    double apply(double price);                     // exactly one abstract method
    default DiscountRule then(DiscountRule next) {  // defaults are allowed
        return p -> next.apply(apply(p));
    }
}

DiscountRule festival = p -> p * 0.9;
DiscountRule coupon = p -> p - 100;
System.out.println(festival.then(coupon).apply(1000));   // 800.0

Predicate: yes-or-no rules

Predicate<T> has boolean test(T t). Use it for rules and filters: validation, search filters, feature flags. Predicates combine with and, or and negate, and Predicate.not (Java 11) reads nicely with method references. stream.filter, removeIf and Optional.filter all take one.

Java
record Order(String id, double amount, boolean paid, String city) {}

Predicate<Order> isPaid = Order::paid;
Predicate<Order> isBig = o -> o.amount() > 5_000;
Predicate<Order> inPune = o -> o.city().equals("Pune");

List<Order> vip = orders.stream()
        .filter(isPaid.and(isBig).or(inPune))       // paid AND big, OR anything in Pune
        .toList();

List<Order> open = new ArrayList<>(orders);
open.removeIf(isPaid);                                // keep only unpaid orders
List<String> filled = names.stream().filter(Predicate.not(String::isBlank)).toList();   // Java 11

Consumer: do something with each item

Consumer<T> has void accept(T t): it takes a value and returns nothing. Use it for side effects: sending, saving, printing, logging. andThen chains consumers. forEach takes a Consumer, and Map.forEach takes a BiConsumer (key and value).

Java
Consumer<String> sendWelcome = email -> System.out.println("Welcome email to " + email);
Consumer<String> audit = email -> System.out.println("Audit: emailed " + email);

List.of("asha@example.com", "ravi@example.com")
        .forEach(sendWelcome.andThen(audit));        // both, in order, for each address

Map.of("java", 3, "sql", 1)
        .forEach((course, seats) -> System.out.println(course + ": " + seats + " seats left"));   // BiConsumer

Supplier: create or fetch a value when needed

Supplier<T> has T get(): no input, one result. Its superpower is laziness: the code inside runs only when (and if) someone calls get(). Use it for defaults that are expensive to compute, factories, and log messages that are costly to build.

Java
Supplier<LocalDateTime> now = LocalDateTime::now;
Supplier<List<String>> newList = ArrayList::new;                 // a factory

String name = Optional.ofNullable(input)
        .orElseGet(() -> loadDefaultNameFromDatabase());           // runs ONLY if input is null
// orElse(loadDefaultNameFromDatabase()) would run the query every time

Logger log = Logger.getLogger("orders");
log.fine(() -> "Order dump: " + expensiveDump(order));           // built only if FINE is enabled

ThreadLocal<SimpleDateFormat> fmt = ThreadLocal.withInitial(() -> new SimpleDateFormat("dd-MM-yyyy"));

Function: transform one thing into another

Function<T, R> has R apply(T t): one input, one output. It's the workhorse for mapping: entities to DTOs, strings to numbers, raw input to clean input. andThen runs another function after it; compose runs one before it; Function.identity() returns its input. stream.map and Map.computeIfAbsent take Functions.

Java
record User(String name, String email) {}
record UserDto(String name) {}

Function<User, UserDto> toDto = u -> new UserDto(u.name());
List<UserDto> dtos = users.stream().map(toDto).toList();

Function<String, String> clean = String::strip;
Function<String, Integer> parse = clean.andThen(Integer::parseInt);   // strip, then parse
System.out.println(parse.apply("  42 "));                             // 42

Map<String, List<String>> byCity = new HashMap<>();
byCity.computeIfAbsent("Pune", city -> new ArrayList<>()).add("Asha");   // Function<String, List<String>>

BiFunction: combine two inputs into a result

BiFunction<T, U, R> has R apply(T t, U u): two inputs, one output. Use it for calculations and merges: price with tax, combining two objects, resolving conflicts. Map.merge, compute and replaceAll take one. When both inputs and the output share a type, BinaryOperator<T> is the shorter name.

Java
BiFunction<Double, Double, Double> withGst = (price, rate) -> price * (1 + rate);
System.out.println(withGst.apply(1000.0, 0.18));                    // 1180.0

BiFunction<Double, Double, String> label = withGst.andThen(p -> "₹" + Math.round(p));
System.out.println(label.apply(1000.0, 0.18));                       // ₹1180

Map<String, Integer> stock = new HashMap<>(Map.of("pen", 10));
stock.merge("pen", 5, Integer::sum);                                 // 15: BinaryOperator<Integer>
stock.compute("pen", (item, qty) -> qty == null ? 1 : qty - 1);      // 14
stock.replaceAll((item, qty) -> qty * 2);                            // 28

Method references

When a lambda only calls an existing method, a method reference is shorter and clearer. There are four kinds:

  1. Static method: Integer::parseInt (same as s -> Integer.parseInt(s))
  2. Method of a particular object: System.out::println
  3. Method of any object of a type: String::toUpperCase (same as s -> s.toUpperCase())
  4. Constructor: ArrayList::new
Java
List<Integer> ids = texts.stream().map(Integer::parseInt).toList();
names.forEach(System.out::println);
List<String> upper = names.stream().map(String::toUpperCase).toList();
Supplier<Set<String>> freshSet = HashSet::new;

Capturing variables

A lambda can use local variables from the enclosing method only if they're effectively final (never reassigned after being set). Inside a lambda, this means the enclosing object, unlike inside an anonymous class.

Java
int limit = 100;                        // effectively final
orders.removeIf(o -> o.amount() > limit);
// limit = 200;                         // would make the lambda above a compile error

Where lambdas show up every day

Collections (forEach, removeIf, replaceAll, sort, computeIfAbsent, merge), streams (filter, map, collect), Optional (map, orElseGet), CompletableFuture (thenApply, thenAccept), executors (submit), comparators (Comparator.comparing) and framework callbacks. Once Predicate, Consumer, Supplier and Function feel natural, most modern Java reads like plain English.

Example

Java
Predicate<String> isLong = s -> s.length() > 5;
Function<String, Integer> len = String::length;
Consumer<String> print = System.out::println;
Supplier<List<String>> fresh = ArrayList::new;

List<String> words = new ArrayList<>(List.of("stream", "map", "lambda", "var"));
words.removeIf(isLong.negate());                  // keep only long words
words.sort(Comparator.comparing(String::length)
                     .thenComparing(Comparator.reverseOrder()));
words.forEach(print);

@FunctionalInterface
interface Discount { double apply(double price); }
Discount festive = p -> p * 0.8;

Old way vs new way

Java 7 anonymous class
Collections.sort(words, new Comparator<String>() {
    @Override
    public int compare(String a, String b) {
        return Integer.compare(a.length(), b.length());
    }
});
Java 8+ lambda and method reference
words.sort(Comparator.comparing(String::length));

Common mistake

Changing a local variable inside a lambda (count++) doesn't compile. Use a stream reduction, an AtomicInteger, or restructure the code.

Under the hood

Lambdas are not anonymous classes under the hood. The compiler emits an invokedynamic call that uses LambdaMetafactory to create the implementation at runtime, and lambdas that capture nothing are reused as singletons. Inside a lambda, this refers to the enclosing object, not to the lambda.

Check yourself

Which interface fits x -> x > 10?

How this connects

Part of Java from zero, Job-ready backend developer, Java 8 and collections, practically.

Was this lesson helpful?

Finished reading? Mark it complete to track your progress.