Quote
一、方法引用:若Lambda体中的内容有方法已经实现了,我们可以使用方法引用 方法引用是Lambda表达式的另外一种表现形式 主要有三种语法格式: 1.对象::实例方法名 2.类::静态方法名 3.类::实例方法名 二、构造器引用: 格式:ClassName::new 三、数组引用: 格式:Type::new
package lambda; import org.junit.Test; import java.util.Comparator; import java.util.function.*; public class TestMethodRef { //对象::实例方法名 @Test public void test1() { Consumer consumer = System.out::println; consumer.accept("aaa"); Employee employee = new Employee("July", 22, 8000); Supplier<String> sup = employee::getName; String str = sup.get(); System.out.println(str); } //类::静态方法名 @Test public void test2() { Comparator<Integer> com = (x, y) -> Integer.compare(x, y); Comparator<Integer> com1 = Integer::compareTo; } //类::实例方法名 @Test public void test3() { BiPredicate<String, String> bp = (x, y) -> x.equals(y); BiPredicate<String, String> bp1 = String::equals; } //构造器引用 @Test public void test4() { Supplier<Employee> emp = () -> new Employee(); Supplier<Employee> emp1 = Employee::new; Employee emp2 = emp1.get(); System.out.println(emp2); Function<Integer, Employee> f1 = Employee::new; Employee f2 = f1.apply(101); System.out.println(f2); BiFunction<String, Integer, Employee> f3 = Employee::new; Employee f4 = f3.apply("张倩", 24); System.out.println(f4); } //数组引用 @Test public void test5() { Function<Integer, String[]> f = (x) -> new String[x]; String[] f1 = f.apply(10); for (int i = 0; i < f1.length; i++) { String s = f1[i]; System.out.println(s); } Function<Integer, String[]> f2 = String[]::new; String[] f3 = f2.apply(10); for (int i = 0; i < f3.length; i++) { String s = f3[i]; System.out.println(s); } } }
Java8 Lambda expression of the new features (d)
Guess you like
Origin blog.csdn.net/qq_38358499/article/details/104641673
Ranking