引用
一、方法引用:若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表達式(四)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.