Lambdas: Tiny Functions

A method without a name

A lambda is a short piece of code you can store in a variable or hand to another method. It looks like this:

(parameters) -> result

import java.util.function.Function;
import java.util.function.Predicate;

public class Main {
    public static void main(String[] args) {
        Function<Integer, Integer> doubleIt = x -> x * 2;
        Predicate<String> isLong = s -> s.length() > 5;

        System.out.println(doubleIt.apply(21));
        System.out.println(isLong.test("Java"));
        System.out.println(isLong.test("Programming"));
    }
}

Output

42
false
true

Think of it like this: A lambda is like a sticky note with an instruction – “double it” – that you hand to someone. They follow the note whenever they need to.

Functional interfaces

A lambda always fills in an interface that has exactly one method (a functional interface). Java has ready-made ones in java.util.function:

InterfaceTakesGives backMethod
Function<T, R>a Tan Rapply
Predicate<T>a Ttrue/falsetest
Consumer<T>a Tnothingaccept
Supplier<T>nothinga Tget
BinaryOperator<T>two T'sa Tapply

Lambdas with collections

Lambdas really shine when you pass them to collection methods:

import java.util.ArrayList;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>(Arrays.asList("ravi", "asha", "meera"));
        names.forEach(n -> System.out.println("Hi " + n));
        names.replaceAll(n -> n.toUpperCase());
        names.sort((a, b) -> a.compareTo(b));
        System.out.println(names);
    }
}

Output

Hi ravi
Hi asha
Hi meera
[ASHA, MEERA, RAVI]

Longer lambdas

If you need more than one line, use curly brackets and return:

import java.util.function.BinaryOperator;

public class Main {
    public static void main(String[] args) {
        BinaryOperator<Integer> safeDivide = (a, b) -> {
            if (b == 0) {
                return 0;
            }
            return a / b;
        };
        System.out.println(safeDivide.apply(10, 2));
        System.out.println(safeDivide.apply(10, 0));
    }
}

Output

5
0

Method references

When a lambda only calls one existing method, you can write it even shorter with :::

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> words = Arrays.asList("one", "two", "three");
        words.forEach(System.out::println);
    }
}

Output

one
two
three

System.out::println means the same as w -> System.out.println(w).

HOME LABS COMMUNITY DASHBOARD