方法引用是一种函数式接口的另一种书写方式
方法引用分为三种,方法引用通过一对双冒号:: 来表示
- 静态方法引用,通过类名::静态方法名, 如 Integer::parseInt
- 实例方法引用,通过实例对象::实例方法,如 str::substring
- 构造方法引用,通过类名::new, 如 User::new
package com.github.mouday.demo; import java.util.function.Function; public class Demo { public static void main(String[] args) { // 使用双冒号:: 引用静态方法 Function<String, Integer> fun = Integer::parseInt; Integer value = fun.apply("20"); System.out.println(value); // 20 // 使用双冒号:: 引用实例方法 String content = "Hello"; Function<Integer, String> func = content::substring; String result = func.apply(1); System.out.println(result); // ello // 使用双冒号:: 引用构造方法 Function<Integer, Integer> intFunc = Integer::new; Integer ret = intFunc.apply(10); System.out.println(ret); // 10 } }
将函数引用作为方法的参数
package com.github.mouday.demo; import java.util.function.Function; public class Demo { public static void main(String[] args) { Demo.sayHello(String::toUpperCase, "Hello"); // HELLO Demo.sayHello(String::toLowerCase, "Hello"); // hello } public static void sayHello(Function<String, String> func, String text) { String result = func.apply(text); System.out.println(result); } }
参考