Lambda基础语法
java8中引入一个新的操作符“->”,该操作符称为箭头操作符或Lambda操作符。
操作符将Lambda表达式拆分为左右两部分:
左侧:Lambda表达式的参数列表
右侧:Lambda表达式中所需执行的功能,称为Lambda体
() -> System.out.println("Hello e路纵横开发团队");
@Test public void test1(){ int num = 0; //匿名内部类 Runnable r = new Runnable() { @Override public void run() { System.out.println("Hello World!" + num);//在匿名内部类中应用了同级别的变量时,在jdk1.7以前,变量必须申明为final,在jdk1.8中,默认加上final } }; r.run(); System.out.println("---------------------------------------"); //Lambda表达式 Runnable r1 = () -> System.out.println("Hello e路纵横开发团队" + num); r1.run(); }
语法格式二:有一个参数,无返回值
(x) -> System.out.prinrln(x);
@Test public void test2(){ Consumer<String> consumer = (x) -> System.out.println(x); consumer.accept("e路纵横"); }
语法格式三:若只有一个参数,小括号可以省略不写
x -> System.out.println(x);
@Test public void test3(){ Consumer<String> consumer = x -> System.out.println(x); consumer.accept("e路纵横"); }
语法格式四:有两个以上的参数,有返回值,并且Lambda体中有多条语句
Comparator<Integer> comparator = (x, y) -> {
System.out.println("函数式接口");
return Integer.compare(x, y);
}
@Test public void test4(){ Comparator<Integer> comparator = (x, y) -> { System.out.println("函数式接口"); return Integer.compare(x, y); }; }
语法格式五:若Lambda体中只有一条语句,return和大括号都可以省略不写
Comparator<Integer> comparator = (x, y) -> Integer.compare(x, y);
@Test public void test5(){ Comparator<Integer> comparator = (x, y) -> Integer.compare(x, y); }
语法格式六:Lambda表达式的参数列表的数据类型可以省略不写,因为JVM编译器可以通过上下文推断出数据类型,即“类型推断”。
(Integer x, Integer y) -> Integer.compare(x, y); 其中Integer可以省略不写
Lambda表达式需要“函数式接口”的支持函数式接口:接口中只有一个抽象方法的接口,称为函数式接口。可以使用注解@FunctionInterface修饰,可以检查接口是否是函数式接口
@FunctionalInterfacepublic interface MyFun<T> { public Integer getValue(Integer num);}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。