A method references Overview
After the previous chapter 2 Lamda Lamda and analytical principles introduced, it will basically familiar with Lamda expression, this time we are more in-depth point. Take a look at reference method.
Method is a shorthand reference to specific Lamda expressions , the idea is that we can replace the Lamda expression directly call the function using the method name.
The syntax is: class name :: method name.
Two three methods cited
1 reference point static method
Syntax: static class name (ClassName) :: method name (MethodName)
Example:
// 1 Lamda静态方法
@Test
public void LamdaSTest(){
String youku1327 = "1327";
Function function = s -> ObjectUtils.allNotNull(youku1327);
System.out.println(function.apply(youku1327));// true
}
// 静态方法引用
@Test
public void MethodRefTest(){
String youku1327 = "youku1327";
Function function = ObjectUtils::allNotNull;
System.out.println(function.apply(youku1327));// true
}
2 a reference to an object example of a method
Syntax: Example Name (instanceName) :: method name (MethodName)
external parameters into the non-target object refers to
an example:
// 2 Lamda表达式
@Test
public void ObjectLamdaTest(){
Car car = new Car("100", "black", "中国", 20);
Supplier supplier = ()-> car.getColor();
System.out.println(supplier.get());//black
}
// 对象引用
@Test
public void ObjectRefTest(){
Car car = new Car("100", "black", "中国", 20);
Supplier<String> supplier = car::getColor;
System.out.println(supplier.get());//black
}
Examples of method reference point 3
Syntax: object name (ClassName) :: name Method (Method)
object refers to an object reference into the
//3 Lamda表达式
@Test
public void InstanceMethodLamdaTest(){
Car car = new Car("100", "black", "中国", 20);
Function<Car,String> function = s -> s.getColor();
System.out.println(function.apply(car));//black
}
@Test
public void InstanceMethodRefTest(){
Car car = new Car("100", "black", "中国", 20);
Function<Car,String> function = Car::getColor;
System.out.println(function.apply(car));//black
}
Three constructors quote
Syntax: object name (ClassName) :: new
@Test
public void constructLamdaTest(){
BiFunction<String,Double,Car> biFunction = (s, aDouble) -> new Car(s,aDouble);
Car car = biFunction.apply("youku1327", 50.0);
// Car(code=youku1327, color=null, factory=null, price=50.0)
System.out.println(car);
}
@Test
public void construcMethodRefTest(){
BiFunction<String,Double,Car> biFunction = Car::new;
Car car = biFunction.apply("youku1327", 50.0);
// Car(code=youku1327, color=null, factory=null, price=50.0)
System.out.println(car);
}
Four micro-channel public number
I feel good writing can focus the next micro-channel public number, more systematic study, we enter the next phase of Stream flow.