Java Language Oracle Official Code Standard Lambda Expressions


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.