JDK1.8Lambda表达式
Lambda 表示式的基础语法: java8中引用新的操作符"->" 该操作称为箭 头操作 Lambda 操作符 表达式拆分成两部门
Lambda
左侧:Lambda 表达式的参数列表
右侧 :Lambda表达式中所需执行的功能 即Lambda 体
1./**
* 语法格式一 无参数,无返回值
* () -> System.out.println("Hello Lambda!")
*/
@Test
public void test1() {
int num = 0;
Runnable b = new Runnable() {
@Override
public void run() {
System.out.println("hello World" + num);
}
};
System.out.println("-----------");
Runnable r1 = () -> System.out.println("hello lambda");
r1.run();
}
2./**
* 语法格式二:
* 有一个参数,并且无返回值
* (x) -> System.out.println(x)
*/
@Test
public void test2() {
Consumer<String> con = x -> System.out.println(x);
con.accept("我大河南");
}
3./**
*语法格式三:若只有一个参数,小括号可以省略不写
* x -> System.out.println(x)
*/
@Test
public void test3() {
Comparator<Integer> com = (x, y) -> {
System.out.println("函数式接口");
return Integer.compare(x, y);
};
}
4./** 语法格式四:
* 有两个以上的参数,并有返回值并且lambda体中有多条语句
* Comparator<Integer> com = (x, y) -> {
* System.out.println("函数式接口");
* return Integer.compare(x,y);
* };
*/
@Test
public void test4() {
Comparator<Integer> com1 = (x, y) -> Integer.compare(x, y);
Comparator<Integer> com = (Integer x, Integer y) -> Integer.compare(x, y);
}
5./** 语法格式五:若Lambda体中只有一条语句,return 和大括号都可以省略不写
* Comparator<Integer> com =(Integer x,Integer y) -> *Integer.compare(x,y);
* 语法格式六:Lambda 表达式的参数列表的数据类型可以省略不写,因为
* JVm编译器通过上下文推断出,数据类型,即"类型推断"
*/
@Test
public void test5() {
// String[] strs ={"aaa","bbb","sss"};
ArrayList<String> list = new ArrayList<>();
show(new HashMap<>());
}
public void show(Map<String, Integer> map) {
}
6./** 语法格式五:若Lambda体中只有一条语句,return 和大括号都可以省略不写
*
*/
@Test
public void test6() {
Integer num =operation(100,(x) -> x * x);
System.out.println(num);
System.out.println(operation(200,(y) -> y + 200));
}
//需求:对一个数进行运算
public Integer operation (Integer num, MyFunction mf){
return mf.getValue(num);
}
// lambda表达式需要"函数式接口"的支持
// 函数式接口:接口中只有一个抽象方法,称为函数式接口可以使用注解@FunctionInterfac
@FunctionalInterface
public interface MyFunction {
public Integer getValue(Integer str);
}