Java8型特性
Java8 新特性 方法引用和构造器引用
方法引用
方法引用:若Lambda表达式体中的内容已经有方法实现了,那么我们可以使用方法引用;也可以认为方法引用是Lambda表达式的另外一种表现形式,这样可以使代码更简洁;
方法引用分类
类型 | 方法引用 | Lambda |
静态方法引用 | 类名::静态方法名 | (args) -> 类名.staticMethod(args) |
实例方法引用 | 对象::实例方法名 | (args) -> 对象.instMethod(args) |
对象方法引用 | 类名::实例方法名 | (inst,args) -> inst.instMethod(args) |
1,静态方法引用
格式:类名::静态方法名
示例:
private void test1() {
//Lambda表达式
Comparator<Integer> comparable = (x,y)->Integer.compare(x,y);
System.out.println(comparable.compare(1,2));
//使用静态方法引用的Lambda表达式
Comparator<Integer> comparable2 = Integer::compare;
comparable2.compare(1,2);
}
2,实例方法引用
格式:对象::实例方法名
示例:
private void test2() {
//Lambda表达式
Consumer<String> consumer = (s) ->System.out.println(s);
consumer.accept("abcdef");
//使用实例方法引用的Lambda表达式
PrintStream ps = System.out;
Consumer<String> consumer1 = ps::println;
consumer1.accept("abcdef");
}
3,对象方法应用
格式:类名::实例方法名
使用条件:若Lambda参数列表中的第一个参数是实例方法的参数调用者,而第二个参数是实例方法的参数时,可以使用对象方法引用。
示例:
private void test3() {
//Lambda表达式
Comparator<String> comparator = (x,y)->x.compareTo(y);
System.out.println(comparator.compare("a","b"));
//使用对象方法引用的Lambda表达式
Comparator<Integer> comparable2 = Integer::compareTo;
comparable2.compare(1,2);
}
构造器引用
格式:类名::new
示例
private void test4() {
//Lambda表达式
Supplier<Map<String,String>> supplier = () -> {return new HashMap<String,String>();};
//使用构造器引用的Lambda表达式
Supplier<Map<String,String>> supplier2 = HashMap::new;
}
数组引用
格式:Type[] ::new
private void test5() {
//Lambda表达式
Function<Integer, Character[]> function = (x) -> new Character[x];
Character[] c = function.apply(10);
System.out.println(c.length);
//使用数组引用的Lambda表达式
Function<Integer, Character[]> function2 = Character[]::new;
Character[] c2 = function.apply(10);
System.out.println(c2.length);
}