liveBook · Manning

Lambda

As explained in The Art of Code

A lambda is an anonymous function value that can be passed, stored, returned, or invoked as data.

A lambda is an anonymous function: a compact way to express behavior without a named class or method. In Java, its arrow separates parameters from the body, and it can implement a functional interface with one abstract method. section 6.2 section 6.2.1

StringPredicate myTestingFunction = x -> x.length() > 3;
boolean isValid = myTestingFunction.test("hello");

This Java lambda implements StringPredicate with the rule that a string must contain more than three characters. section 6.2.1

List<StringPredicate> myFunctions = List.of(x -> x.length() > 3, 
   x -> x.equals("Hello"));
boolean isValid = myFunctions.getFirst().test("For the demo");

A list can hold lambdas as values, which can then be retrieved and invoked. section 6.2.1

Functions can also be passed to other functions or returned from them. Lambdas make these uses concise, but brevity is not always clarity: choose a lambda when its behavior is easy to follow, and prefer a more explicit loop or extracted method when it is not. section 6.2.1 section 5.2

How The Art of Code covers it

How deep it goes
Explains arrow syntax, functional-interface use, and first-class functions through examples across several languages.
Examples
Shows a string-length predicate, lambdas stored in a list, and alternatives for iterating over publication dates.
What it assumes
Relates lambdas to single-method functional interfaces and explains how they replace a named class implementation.
What you can do after
Apply lambdas to implement functional interfaces and pass, store, return, or invoke behavior as data.
How it connects
Connects lambdas to functional interfaces, first-class functions, functional programming, and method references.

Also explained in

Compare how 20 books explain lambda →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Art of Code. The section links point to the parts of the book it draws on.