All lessons

Power Tools: Lambdas & Streams

10 min · Java

Write inline functions with lambdas and transform lists with the Streams API.

Java · Power Tools: Lambdas & Streams0/5 cleared

Enemy 1 of 5

Every method you've written so far has a name, declared once at the top level of the class. A lambda is a compact, unnamed function you can write inline, right where you need it: parameters -> expression, with no method name, no explicit return type, and no return keyword — whatever the expression evaluates to is automatically the result.

Because Java requires every value to have a type, a lambda has to be assigned to something called a functional interface — an interface with exactly one method, like Function<Integer, Integer>, which describes "a thing that takes an Integer and gives back an Integer." Once assigned, you call .apply() to actually run the lambda, passing in the argument.

Lambdas were added to Java in Java 8 specifically to make this kind of short, throwaway logic much less verbose than writing out an entire named method (or an anonymous inner class, the old way of achieving something similar) just to double a number. They're most useful exactly like this: brief logic handed straight to another operation, such as the stream methods below.

You
Binary Treant

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: 36