# Lambdas and Functional Interfaces in Java — In Depth, with Method References

Source: https://skills101.in/learn/java/java-lambdas-functional-interfaces — Skills101 free tutorial (Java Programming). Updated 2026-11-21.

The [Java 8 lesson](https://skills101.in/learn/java/java-8-lambdas-streams) showed what a lambda is and how streams use them. This lesson goes deeper: how to read any lambda, which built-in interface to choose, how to **combine** small functions into bigger ones, and the four kinds of **method references**. These are exactly the points that output-prediction questions and interview follow-ups test.

## 1. A lambda is an object that implements one method

A **functional interface** is an interface with **exactly one abstract method**. A lambda is a short way to create an object of such an interface: you write only the method's parameters and body.

```java
@FunctionalInterface
interface Discount {
    double apply(double price);
}

public class Main {
    public static void main(String[] args) {
        Discount festive = price -> price * 0.8;          // 20% off
        Discount flat = price -> Math.max(0, price - 150); // ₹150 off, never below 0
        double[] carts = {1000, 100};
        for (double c : carts) {
            System.out.println(c + " -> festive " + festive.apply(c) + ", flat " + flat.apply(c));
        }
    }
}
```

```text
1000.0 -> festive 800.0, flat 850.0
100.0 -> festive 80.0, flat 0.0
```

`@FunctionalInterface` is optional, but it makes the compiler complain if someone adds a second abstract method later. Default and static methods do not count — `Comparator` has many of those and is still functional.

### All the syntax forms

| Form | Example |
|---|---|
| no parameters | `() -> "hello"` |
| one parameter (brackets optional) | `x -> x * x` |
| several parameters | `(a, b) -> a + b` |
| with types | `(int a, int b) -> a + b` |
| block body (needs `return`) | `(a, b) -> { int s = a + b; return s * 2; }` |

An expression body returns its value automatically; a block body `{ … }` needs an explicit `return` if the method returns something.

## 2. The java.util.function family

You rarely need to write your own interface. The package `java.util.function` has ready ones for the common shapes.

![The main functional interfaces by shape: Supplier takes nothing and gives T; Consumer takes T and gives nothing; Predicate takes T and gives boolean; Function takes T and gives R; UnaryOperator takes T and gives T; BiFunction takes T and U and gives R; BinaryOperator takes two T and gives T](https://skills101.in/learn-img/java/functional-family.svg)

| Interface | Method | Shape | Typical use |
|---|---|---|---|
| `Supplier<T>` | `get()` | () → T | create a default value lazily |
| `Consumer<T>` | `accept(t)` | T → nothing | print, save, send |
| `Predicate<T>` | `test(t)` | T → boolean | filter, check a rule |
| `Function<T, R>` | `apply(t)` | T → R | convert, map |
| `UnaryOperator<T>` | `apply(t)` | T → T | change a value of the same type |
| `BiFunction<T, U, R>` | `apply(t, u)` | (T, U) → R | combine two values |
| `BinaryOperator<T>` | `apply(a, b)` | (T, T) → T | sum, max, merge (`reduce`) |

For primitives there are versions without boxing: `IntPredicate`, `IntUnaryOperator`, `IntBinaryOperator`, `ToIntFunction<T>` and so on. Prefer them in number-heavy code.

```java
import java.util.function.*;

public class Main {
    public static void main(String[] args) {
        UnaryOperator<String> shout = s -> s.toUpperCase() + "!";
        BinaryOperator<Integer> bigger = (a, b) -> a >= b ? a : b;
        BiFunction<String, Integer, String> repeat = (s, n) -> s.repeat(n);
        IntPredicate isEven = n -> n % 2 == 0;           // no Integer boxing
        Supplier<double[]> emptyMarks = () -> new double[3];

        System.out.println(shout.apply("placed"));
        System.out.println(bigger.apply(72, 91));
        System.out.println(repeat.apply("ab", 3));
        System.out.println(isEven.test(10) + " " + emptyMarks.get().length);
    }
}
```

```text
PLACED!
91
ababab
true 3
```

## 3. Combining functions

The built-in interfaces have **default methods** that join small functions into bigger ones — without writing new classes.

![Function composition: f is x plus 2 and g is x times 10. f.andThen(g) runs f first then g, so 3 becomes 5 then 50. f.compose(g) runs g first then f, so 3 becomes 30 then 32](https://skills101.in/learn-img/java/compose-andthen.svg)

```java
import java.util.function.*;

public class Main {
    public static void main(String[] args) {
        Function<Integer, Integer> addTwo = x -> x + 2;
        Function<Integer, Integer> timesTen = x -> x * 10;
        System.out.println(addTwo.andThen(timesTen).apply(3));   // (3 + 2) * 10
        System.out.println(addTwo.compose(timesTen).apply(3));   // 3 * 10 + 2

        Predicate<Integer> passed = m -> m >= 40;
        Predicate<Integer> distinction = m -> m >= 75;
        Predicate<Integer> passNoDistinction = passed.and(distinction.negate());
        for (int m : new int[]{35, 60, 88}) {
            System.out.print(m + ":" + passNoDistinction.test(m) + " ");
        }
        System.out.println();

        Consumer<String> log = s -> System.out.print("[log] " + s);
        Consumer<String> done = s -> System.out.println(" ... saved");
        log.andThen(done).accept("order 101");
    }
}
```

```text
50
32
35:false 60:true 88:false 
[log] order 101 ... saved
```

- `f.andThen(g)` = "do f, **then** g". `f.compose(g)` = "do g **first**, then f".
- `Predicate` has `and`, `or`, `negate`, and the static `Predicate.not(p)`.
- `Consumer.andThen` runs two actions one after the other on the same value.

## 4. Method references: four kinds

When a lambda only calls one existing method, a **method reference** (`::`) says the same thing more briefly.

| Kind | Method reference | Same as the lambda |
|---|---|---|
| static method | `Integer::parseInt` | `s -> Integer.parseInt(s)` |
| method of a **particular** object | `prefix::concat` | `s -> prefix.concat(s)` |
| method of **any** object of a type | `String::length` | `s -> s.length()` |
| constructor | `StringBuilder::new` | `s -> new StringBuilder(s)` |

```java
import java.util.*;
import java.util.function.*;

public class Main {
    public static void main(String[] args) {
        Function<String, Integer> parse = Integer::parseInt;          // static
        String prefix = "Roll-";
        Function<String, String> tag = prefix::concat;                 // particular object
        Function<String, Integer> len = String::length;                // any object
        BiFunction<String, String, Boolean> same = String::equalsIgnoreCase; // any object, 2 args
        Function<String, StringBuilder> make = StringBuilder::new;     // constructor

        System.out.println(parse.apply("41") + 1);
        System.out.println(tag.apply("007"));
        System.out.println(len.apply("Skills101"));
        System.out.println(same.apply("JAVA", "java"));
        System.out.println(make.apply("abc").reverse());

        List<String> names = new ArrayList<>(List.of("ravi", "asha", "om"));
        names.replaceAll(String::toUpperCase);
        names.forEach(System.out::println);
    }
}
```

```text
42
Roll-007
9
true
cba
RAVI
ASHA
OM
```

The trickiest one is the third kind: in `String::equalsIgnoreCase`, the **first** argument becomes the object the method is called on, and the second becomes its parameter.

## 5. Capturing variables and returning lambdas

A lambda can use local variables from the surrounding method only if they are **effectively final** (never changed after being set). It can freely read and change **fields**. A method can also **return** a lambda, which lets you build functions from settings:

```java
import java.util.function.*;

public class Main {
    static int callCount = 0;                       // a field: lambdas may change it

    static IntUnaryOperator multiplier(int factor) {
        return x -> {
            callCount++;
            return x * factor;                      // factor is captured
        };
    }

    public static void main(String[] args) {
        IntUnaryOperator twice = multiplier(2);
        IntUnaryOperator thrice = multiplier(3);
        System.out.println(twice.applyAsInt(21) + " " + thrice.applyAsInt(21));
        System.out.println("calls: " + callCount);

        int bonus = 5;
        // bonus++;                                  // would break the next line
        IntUnaryOperator addBonus = m -> m + bonus;
        System.out.println(addBonus.applyAsInt(70));
    }
}
```

```text
42 63
calls: 2
75
```

Each call to `multiplier` returns a new function that **remembers** its own `factor`. Why must captured locals be effectively final? The lambda may run later, even on another thread, after the method has returned and its local variables are gone; Java copies the value, so it must not change.

## Common mistakes

- Writing a block body without `return`: `x -> { x * 2; }` does not compile.
- Mixing up `andThen` and `compose` — read `compose` as "run the argument first".
- Changing a local variable that a lambda uses (compile error "must be final or effectively final").
- Using `Function<Integer, Integer>` in heavy number loops instead of `IntUnaryOperator`, causing boxing.
- Long, multi-line lambdas: move the logic into a named method and use a method reference.

## Quick recap

- A lambda implements the single abstract method of a functional interface.
- Built-ins: Supplier, Consumer, Predicate, Function, UnaryOperator, BiFunction, BinaryOperator, plus Int/Long/Double versions.
- Combine: `andThen`, `compose`, `and`, `or`, `negate`.
- Method references: static, particular object, any object of a type, constructor.
- Captured local variables must be effectively final; lambdas can be returned from methods.


Practice quiz and free certificate: https://skills101.in/learn/java/java-lambdas-functional-interfaces