@Test public void test1(){ new Thread(new Runnable() { @Override public void run() { System.out.println("以前大家都这么写"); } }).start(); //使用lambda表达式 new Thread(()->{ System.out.println("我是一个小栗子,现在可以这么写"); }).start(); } 复制代码
//无参数无返回值 Runnable runnable1=()->{ System.out.println("hhh"); System.out.println("yingyingying") }; //只有一个参数 Consumer<String> con2 = s -> System.out.println(s) //两个参数,类型推断,省掉return,{} Comparator<Integer> comparator = (o1,o2) -> o1.compareTo(o2); 复制代码
User user = new User(); Supplier<String> sup1 = () -> user.getName(); Supplier<String> sup=()->user::getName; PrintStream ps=System.out; Consumer<String> consumer = ps::println; 复制代码
Comparator<Integer> com1 = (t1,t2) -> Integer.compare(t1,t2); Comparator<Integer> com1 = Integer::compare; Function<Double,Long> func1 = d -> Math.round(d); Function<Double,Long> func2 = Math::round; 复制代码
Comparator<String> com1 = (s1,s2) -> s1.compareTo(s2); Comparator<String> com2 = String :: compareTo; BiPredicate<String,String> pre1 = (s1,s2) -> s1.equals(s2); BiPredicate<String,String> pre2 = String :: equals; Function<Employee,String> func1 = e -> e.getName(); Function<Employee,String> func2 = Employee::getName; 复制代码
Supplier<Employee> sup1 = () -> new Employee(); Supplier<Employee> sup2 = Employee :: new; Function<Integer,Employee> func1 = id -> new Employee(id); Function<Integer,Employee> func2 = Employee :: new; BiFunction<Integer,String,Employee> func1 = (id,name) -> new Employee(id,name); BiFunction<Integer,String,Employee> func2 = Employee :: new; 复制代码
Function<Integer,String[]> func1 = length -> new String[length]; Function<Integer,String[]> func2 = String[] :: new; String[] arr1 = func1.apply(5); 复制代码
当然啦!需要表明自己定义的接口是函数式接口,那么啥时函数式接口呢? 如果一个接口中,只声明了一个抽象方法,则此接口就称为函数式接口,需在上面添加@FunctionalInterface 注解。
//自己定义的函数式接口 @FunctionalInterface public interface MyInterface { void method1(); } @Test public void test3(){ MyInterface myInterface = ()-> System.out.println("hhh"); myInterface.method1(); } 复制代码
函数式接口 | 参数类型 | 返回类型 | 用途 |
---|---|---|---|
Consumer | T | void | 对类型为T的对象应用操作,包含方法void accept(T t) |
Supplier | 无 | T | 返回类型为T的对象,包含方法:T get() |
Function<T, R> | T | R | 对类型为T的对象应用操作,并返回结果。结果是R类型的对象。包含方法:R apply(T t) |
Predicate | T | boolean | 确定类型为T的对象是否满足某约束,并返回 boolean值。包含方法:boolean test(T t) |
方法引用本质上时Lambda表达式->Lambda表达式本质上是函数式接口的实例->函数式接口的实例就是对象->Java OOP思想!