Lambda expressions
Lambda is an anonymous function, we can put Lambda expressions it can be understood as a piece of code passed (pass code that will be the same as the data). You can write simpler, more flexible code. As a more compact code style, the Java language skills has improved.
Lambda expressions left: Lambda expressions argument list;
right Lambda expressions: Function Lambda expressions need to be performed, i.e. Lambda body;
Lambda expression syntax
- A syntax: no parameters, no return value
public void test1(){
int num = 0; //匿名函数用成员变量,jdk1.7前,必须final修饰
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Hello World!" + num);
}
};
r.run();
//Lambda表达式写法
Runnable r1 = () -> System.out.println("Hello Lambda!");
r1.run();
}
- Two syntax: There is a parameter, and no return value
public void test2(){
//Consumer 消费型接口 属于Java8 内置的四大核心函数式接口之一
//若只有一个参数,小括号可以省略不写
//Consumer<String> con = (x) -> System.out.println(x);
Consumer<String> con = x -> System.out.println(x);
con.accept("武汉加油!");
}
- Three syntax: two or more parameters, return values, and more than one statement Lambda body
public void test3(){
Comparator<Integer> com = (x, y) -> {
System.out.println("函数式接口");
return Integer.compare(x, y);
};
}
- Syntax four: Lambda body if only one statement, return and curly braces can be omitted
public void test4(){
Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
}
- Syntax five: data type parameter list of Lambda expressions can be omitted, because the JVM compiler infer from the context, data types, namely "type inference"
public void test5(){
//String[] strs;
//strs = {"aaa", "bbb", "ccc"};
List<String> list = new ArrayList<>();
show(new HashMap<>());
}
public void show(Map<String, Integer> map){
}
Two, Lambda expressions need to support "function interface" of the
function interface: The interface is only one interface abstract method, called functional interface. You can use annotations @FunctionalInterface modification, you can check whether the function interface
@FunctionalInterface //函数式接口的注解
public interface MyFun {
public Integer getValue(Integer num);
}
//对一个数进行运算
@Test
public void test6(){
System.out.println(operation(100, (x) -> x * x));
System.out.println(operation(200, (y) -> y + 200));
}