1.8 新特性之 Lambda Expressions
Lambda expressions are allowed only at source level 1.8 or above
The target type of this expression must be a functional interface
https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
lambda n. /ˈlæmdə/ 希臘字母表的第11個字母 (Λ, λ)
由來:
One issue with anonymous classes is that if the implementation of your anonymous class is very simple, such as an interface that contains only one method, then the syntax of anonymous classes may seem unwieldy and unclear. In these cases, you're usually trying to pass functionality as an argument to another method, such as what action should be taken when someone clicks a button. Lambda expressions enable you to do this, to treat functionality as method argument, or code as data.
The previous section, Anonymous Classes, shows you how to implement a base class without giving it a name. Although this is often more concise than a named class, for classes with only one method, even an anonymous class seems a bit excessive and cumbersome. Lambda expressions let you express instances of single-method classes more compactly.
應用物件(functional interface)
A functional interface is any interface that contains only one abstract method.
語法:
- A comma-separated list of formal parameters enclosed in parentheses.
- The arrow token,
->
- A body, which consists of a single expression or a statement block.
舉例(引數型別可以省略,單引數可省略() parentheses,單語句可省{}brace):
import org.junit.Test; public class SomeoneTest { @Test public void test1() { Someone a = new Someone() { @Override public String doSomething(String arg) { return "::" + arg; } }; System.out.println(a.doSomething("a")); } @Test public void test2() { Someone b = (String arg) -> { return "::" + arg; }; System.out.println(b.doSomething("b")); } @Test public void test3() { Someone c = arg -> "::" + arg; System.out.println(c.doSomething("c")); } } interface Someone { String doSomething(String arg); }
多引數必須加()
import org.junit.Test; public class DogTest { @Test public void test1() { Dog a = (s1, s2) -> { System.out.println(s1 + s2); }; a.bark("wang", "wang"); } @Test public void test2() { Dog b = (s1, s2) -> System.out.println(s1 + s2); b.bark("wang", "wang"); } } interface Dog { void bark(String s1, String s2); }
無引數必須是 () ->
import org.junit.Test; public class CatTest { @Test public void test1() { Cat a = () -> System.out.println("miao~"); a.meow(); } } interface Cat { void meow(); }
更多高階用法見 package java.util.function;