1.方法引用包含三种:
(1)对象::函数名
(2)类::静态函数名
(3)类::函数名
ps.
a. lambda体中调用方法的参数列表与返回值类型,要与函数式接口中抽象方法的函数列表和返回值是一致的。
b.(3)对形参有要求,形参1和形参2在lambda表达式中形参1调用某函数,某函数形参是形参2。
2.构造器引用
调用构造器参数列表要与函数式接口抽象方法参数一致。
3.数组引用
import java.util.*;
import java.util.function.*;
/**
* Created by zhangtuo on 2017/7/16.
*/
public class TestLambda {
/**
* 1.方法引用:
* NO.1 对象::实例方法名
*/
public void test1() {
Entity entity = new Entity();
Consumer con = (x)->entity.setX(x);
Consumer con2 = entity::setX;
Consumer con3 = new Entity()::setX;
con.accept(23);
con2.accept(23);
}
/**
* 1.方法引用:
* NO.2 类::静态函数名
*/
public void test2() {
Comparator com = (x, y)->Integer.compare(x, y);
Comparator com2 = Integer::compare;
com.compare(1,2);
com2.compare(1,2);
}
/**
* 1.方法引用:
* NO.3 类::函数名(形参1和形参2在lambda表达式中形参1调用某函数,某函数形参是形参2)
*/
public void test3() {
BiPredicate bp = (x, y)->x.equals(y);
BiPredicate bp2 = String::equals;
bp2.test("x","y");
BiFunction bf = (x,y)->x.compare(y);
bf.apply(new Entity(), new Entity());
BiFunction bf2 = Entity::compare;
bf2.apply(new Entity(2), new Entity(3));
}
/**
* 2.构造器引用:空构造器
*/
public void test5() {
Supplier sup = ()->new ArrayList<>();
Supplier sup2 = ArrayList::new;
sup.get();
sup2.get();
}
/**
* 2.构造器引用:带参数构造器
*/
public void test6() {
Function fun = (x)->new ArrayList(x);
Function fun2 = ArrayList::new;
fun.apply(2);
fun2.apply(2);
BiFunction bf = Entity::new;
bf.apply(1,2);
}
/**
* 3.数组引用
*/
public void test7() {
Function fun = (x)->new String[x];
Function fun2 = String[]::new;
}
}
class Entity {
int x;
int y;
Entity() {
}
Entity(int x) {
this.x = x;
}
Entity(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public Integer compare(Entity entity) {
if (entity != null)
return 1;
return 0;
}
}