Java Language Oracle Official Code Standard Lambda Expressions

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Runnable r = () -> System.out.println("Hello World");

Supplier<String> c = () -> "Hello World";

// Collection::contains is a simple unary method and its behavior is
// clear from the context. A method reference is preferred here.
appendFilter(goodStrings::contains);

// A lambda expression is easier to understand than just tempMap::put in this case
trackTemperature((time, temp) -> tempMap.put(time, temp));
  • Expression lambdas are preferred over single-line block lambdas.
  • Method references should generally be preferred over lambda expressions.
  • For bound instance method references, or methods with arity greater than one, a lambda expression may be easier to understand and therefore preferred. Especially if the behavior of the method is not clear from the context.
  • The parameter types should be omitted unless they improve readability.
  • If a lambda expression stretches over more than a few lines, consider creating a method.


Got any Java Language Question?