Lambda语法格式(学习笔记)
package com.atguigu.java8;
import org.testng.annotations.Test;
import java.util.*;
import java.util.function.Consumer;
public class TestLambda2 {
// 语法格式一:无参数,无返回值
@Test
public void test1(){
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Hello world!");
}
};
r.run();
System.out.println("------------------");
Runnable r1 = () -> System.out.println("Hello Lambda!");
r1.run();
}
// 语法格式二:有一个参数,无返回值
@Test
public void test2(){
Consumer con = (x) -> System.out.println(x);
con.accept("ababababa");
}
// 语法格式三;有多个参数,并且有返回值,有多条语句,必须使用大括号
@Test
public void test3(){
Comparator com = (x, y) -> {
System.out.println("Hello world!");
return Integer.compare(x,y);
};
com.compare(12,232);
System.out.println(com);
}
// 语法格式四;多个参数,只有一个返回语句,大括号和return可以省略
@Test
public void test4(){
Comparator com = (x, y) -> Integer.compare(x,y);
}
@Test
public void test5(){
String[] str = {"s","f"};
String[] str1 = {"a","d"};
List list = new ArrayList<>();
show(new HashMap<>());
}
public void show(Map mp){
}
// 利用Lambda表达式实现前提需要函数接口,实现了重复利用
@Test
public void test6(){
Integer num = operation(100, (x) -> x * x);
System.out.println(num);
Integer num2 = operation(200, (x) -> x + 200);
System.out.println(num2);
}
public Integer operation(Integer num, MyFun mf){
return mf.getValue(num);
}
}