1.8 新特性之 Lambda Expressions

时间:2022-11-04 19:27:34

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.

语法:

  1. A comma-separated list of formal parameters enclosed in parentheses.
  2. The arrow token, ->
  3. 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;