Lambda 表示式

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));
  • 表達 lambda 優於單線 block lambdas。
  • 方法引用通常應優先於 lambda 表示式。
  • 對於繫結例項方法引用或 arity 大於 1 的方法,lambda 表示式可能更容易理解,因此更受歡迎。特別是如果從上下文中不清楚方法的行為。
  • 除非提高可讀性,否則應省略引數型別。
  • 如果 lambda 表示式延伸超過幾行,請考慮建立一個方法。