# Lambda 表示式與函式介面

`Comparator<String> byLength = (String name1, String name2) -> name1.length() - name2.length();`

`(String name1, String name2) -> name1.length() - name2.length()`

```(String name1, String name2) -> {     String n1 = name1.trim();     String n2 = name2.trim();     ...     return n1.length() - n2.length();    }```

```() -> "Justin" // 不接受參數，傳回字串 () -> System.out.println() // 不接受參數，沒有傳回值 ```

`Comparator<String> byLength = (name1, name2) -> name1.length() - name2.length();`

Lambda表示式本身是中性的，不代表任何一種物件，同樣的Lambda表示式，可用來表示不同目標型態的物件實作，舉例而言，`(name1, name2) -> name1.length() - name2.length()`在上面的範例中，用來表示`Comparator<String>`實例，如果你定義了一個介面：

```public interface Func<P, R> {     R apply(P p1, P p2); }```

`Func<String, Integer> func = (name1, name2) -> name1.length() - name2.length();`

```public interface Runnable {     void run(); }   public interface Callable<V> {     V call() throws Exception; }   public interface Comparator<T> {     int compare(T o1, T o2); }```

```Arrays.sort(names, new Comparator<String>() {     public int compare(String name1, String name2) {         return name1.length() - name2.length();     } });```

`Arrays.sort(names, (name1, name2) -> name1.length() - name2.length());`

```public interface Func {     public void apply(String s); }```

`Func f = (s) -> System.out.println(s);`

`Func f = s -> System.out.println(s);`

```@FunctionalInterface public interface Func<P, R> {     R apply(P p); }```

```@FunctionalInterface public interface Function<P, R> {     R call(P p);     R call(P p1, P p2); }```

@FunctionalInterface
^
Function is not a functional interface
multiple non-overriding abstract methods found in interface Function
1 error

Lambda語法不過就是匿名類別的編譯器語法蜜糖嘛！？接下來會探討更多細節，你就知道不是了！