Java Lambda Cheat Sheet
Lambda Expressions
Used to contruct implementations of Functional Interfaces without explicitly creating new classes and instances. All functional interfaces implement exactly one method, which allows for syntactic sugar to implement that one method with much less code.
() -> expression | statement param -> expression | statement (params) -> expression | statement (params) -> { expressions and statements } (types) (params) -> { expressions and statements }
- optional types before parameters
- final and annotations can be used on typed parameters
() -> System.out.println("I'm a function that prints this statement.");
a -> a * 2 // calculate double of a (idiomatic) (a) -> a * 2 // without the type, with parens (int a) -> a * 2 // with type and parens (final int a) -> a * 2 // with final, type and parens (final only works with a type) (@NonNull int a) -> a * 2 // with an annotation, type and parens (annotations only work with a type)
(a, b) -> a + b // Sum of 2 parameters, inferred types (idiomatic) (int a, int b) -> a + b // Sum of 2 parameters, explicit types (int, int) (tx, status) -> a + b // explicit types, alternate syntax
If the lambda is more than one expression, we must use { }
and return
(x, y) -> { int sum = x + y; int avg = sum / 2; return avg; }
Within a lambda, you can reference only parameters and final variables from the outer scope.
A lambda expression cannot stand alone in Java, it need to be associated to a functional interface.
@FunctionalInterface interface MyMath { int getDoubleOf(int a); } MyMath d = a -> a * 2; // associated to the interface d.getDoubleOf(4); // is 8
Useful functions
Return the input parameter
x -> x // or Function.identity()
Method and Constructor References
Allows referencing methods and constructors without writing an explicit lambda function
// Lambda Form: getPrimes(numbers, a -> StaticMethod.isPrime(a)); // Method Reference: getPrimes(numbers, StaticMethod::isPrime);
Style | Method Reference | Lambda Form |
---|---|---|
Class::staticMethod | MyClass::staticMethod | n -> MyClass.staticMethod(n) |
Class::instanceMethod | String::toUpperCase | (String w) -> w.toUpperCase() |
… | String::compareTo | (String s, String t) -> s.compareTo(t) |
… | System.out::println | x -> System.out.println(x) |
instance::instanceMethod | manager::getByID | (int id) -> manager.getByID(id) |
this::instanceMethod | this::getValueByID | (int id) -> this.getValueByID(id) |
super::instanceMethod | super::aMethodThatIveOverridden | (int id) -> super.aMethodThatIveOverridden(id) |
Class::new | Double::new | n -> new Double(n) |
Class[]::new | String[]::new | (int n) -> new String[n] |
primitive[]::new | int[]::new | (int n) -> new int[n] |