Java Tutorial

Java Lambdas

A lambda is a short anonymous function — (args) -> body — that implements a functional interface where a method is expected.

Shape of a lambda

Write parameters, an arrow, and a body. The target type is a functional interface — one abstract method — such as Runnable, Comparator, or Predicate.

Example

import java.util.List;

public class Main {
  public static void main(String[] args) {
    List names = List.of("Ada", "Lin", "Max");
    names.forEach(n -> System.out.println(n));
  }
}

With streams and predicates

Lambdas shine as arguments to filter, map, and removeIf. Keep them short — a few lines of logic, not a whole method body.

Example

import java.util.ArrayList;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    List nums = new ArrayList<>(List.of(1, 2, 3, 4, 5));
    nums.removeIf(n -> n % 2 == 0);
    nums.replaceAll(n -> n * 10);
    System.out.println(nums);   // [10, 30, 50]
  }
}

Method references

When a lambda only calls an existing method, a method reference is clearer:String::toUpperCase, System.out::println.

Example

import java.util.List;

public class Main {
  public static void main(String[] args) {
    List.of("a", "b", "c").stream()
        .map(String::toUpperCase)
        .forEach(System.out::println);
  }
}

Capture only final or effectively final local variables inside a lambda. Reassigning a local and then using it in a lambda is a compile error.

Your own functional interface

Any interface with a single abstract method can be implemented by a lambda. Mark it@FunctionalInterface so the compiler checks that rule.

Example

@FunctionalInterface
interface IntOp {
  int apply(int a, int b);
}

public class Main {
  public static void main(String[] args) {
    IntOp add = (a, b) -> a + b;
    IntOp mul = (a, b) -> a * b;
    System.out.println(add.apply(2, 3));
    System.out.println(mul.apply(2, 3));
  }
}

Prefer the ready-made types in java.util.function (Function,Predicate, Consumer) over inventing new interfaces for every one-liner.

Try It Yourself

Exercise: Sort a List<String> by length using list.sort((a, b) -> ...) and print the result.

Show solution
import java.util.ArrayList;
import java.util.List;

List words = new ArrayList<>(List.of("pear", "fig", "apple"));
words.sort((a, b) -> a.length() - b.length());
System.out.println(words);   // [fig, pear, apple]

The comparator lambda returns a negative number when a is shorter, so shorter words come first.

Key Takeaways

  • Lambdas implement functional interfaces: (args) -> body.
  • They power streams, forEach, sort, and removeIf.
  • Method references replace trivial lambdas that only call one method.
  • Captured locals must be final or effectively final.

Worked examples

The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.

Open them in the Java editor at /java/try. Change one measurement and check whether the result still has the right unit.

Maths

Square each term

A lambda is a tiny function you pass to forEach. Here each integer is squared and printed.

Example

import java.util.List;

public class Main {
  public static void main(String[] args) {
    List.of(1, 2, 3, 4).forEach(n -> System.out.print((n * n) + " "));
    System.out.println();
  }
}

FAQ: Java Lambdas

Common questions about this page.

What is the StudyGrid Java tutorial?

The StudyGrid Java tutorial is a full beginner-to-advanced track: syntax, types, input, loops, methods, classes, collections, generics, maps, and lambdas. Each chapter has copy-and-run examples.

Should I run java lambda examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn java lambda in this Java Java lesson (Java Lambdas).

Is the Java editor the same as Try Python or Try C++?

No. Try Java compiles with javac at /java/try and shows stdout plus compiler messages. Try Python stays at /try. Try C++ stays at /cpp/try. Java lessons never open those editors.

Do I need to install a JDK to learn Java?

No. Open a chapter, click Try it in Java, and compile in the browser. You can also download a .java file and compile locally with javac.

Where should I start the Java tutorial?

Start at Java Intro, then Get Started and Syntax. After the first program, continue to output, variables, and if-else. After classes, open Java Examples, then generics, map, and lambdas. Use Next at the bottom of each chapter.

Is the Java tutorial free?

Yes. The Java workshop on StudyGrid (studygrid.in) is free: dashboard, chapters, and the compile-and-run editor.