package com.expgiga.Java8; /** * */ @FunctionalInterface public interface MyFunction { public Integer getValue(Integer num); }
package com.expgiga.Java8; import java.net.Inet4Address; import java.util.Comparator; import java.util.function.Consumer; /** * Java8 Lambda基础语法: * Java8中引入了新的操作符:->,该操作符称为箭头操作符或者Lambda操作符 * ->左侧:Lambda表达式的参数列表 * ->右侧:Lambda表达式中所需要执行的功能,Lambda体 * * 语法: * 格式1:无参数,无返回值 * () -> System.out.println("Hello Lambda!") * * 格式2:一个参数,无返回值 * (x)-> System.out.println(x); * * 格式3:若只有一个参数,那么参数的小括号可以省略不写。 * * * 格式4:有两个以上的参数,有返回值,并且Lambda体中,有多条语句 * * 格式5:Lambda中只有一条语句,return和大括号都可以省略不写 * * 格式6:Lambda的参数列表的数据类型可以省略不写,因为JVM可以根据上下文进行类型推断。 * * * Lambda需要函数式接口的支持: * 函数式接口:接口中只有一个抽象方法的接口,称为函数式接口。可以使用@FunctionInterface修饰 * 可以检查是否是函数式接口 */ public class TestLambda2 { public static void main(String[] args) { //格式1: /* * 注意事项:在jdk1.8以前,在局部匿名类中使用了同级别的变量时,该变量必须是final */ int num = 100; //jdk1.8以前必须是final,此处其实也是final的,只是没有写final,测试的话,num++是不行的! Runnable r = new Runnable() { @Override public void run() { System.out.println("Hello Lambda!" + num); } }; r.run(); System.out.println("----------------------"); Runnable r1 = () -> System.out.println("Hello Lambda!"); r1.run(); //格式2: Consumer<String> con = (x) -> System.out.println(x); con.accept("你牛逼"); //格式4: Comparator<Integer> com = (x, y) -> { System.out.println("函数式接口:"); return Integer.compare(x, y); }; //格式5: Comparator<Integer> comm = (x, y) -> Integer.compare(x, y); //需求:对一个数进行运算 Integer integer = operation(100, (x) -> x * x); System.out.println(integer); } private static Integer operation(Integer num, MyFunction mf) { return mf.getValue(num); } }