Java 8 method references and construction reference code instances
This article mainly introduces java8 method reference and construction reference code examples. The example code is introduced in great detail, which has certain reference value for everyone's study or work. Friends in need can refer to it
I. overview of method reference
Method reference is a shorthand for a specific lamda expression. Its idea is to directly call the function and use the method name if it can replace the lamda expression. Its syntax format: Class Name:: method name.
II. Three methods of reference
1 reference to static method
Syntax format: static class name: method name
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 reference to the method of the object instance
Syntax format: instance name: method name
This object refers to an external object that is not an input parameter
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",20); supplier<String> supplier = car::getColor; System.out.println(supplier.get());//black }
3 method reference to instance
Syntax format: object name (classname):: method name. This object refers to the input parameter object
//3 Lamda表达式 @Test public void InstanceMethodLamdatest(){ Car car = new Car("100",20); Function<Car,String> function = s -> s.getColor(); System.out.println(function.apply(car));//black } @Test public void InstanceMethodReftest(){ Car car = new Car("100",String> function = Car::getColor; System.out.println(function.apply(car));//black }
Three constructor references
Syntax format: 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,Car> biFunction = Car::new; Car car = biFunction.apply("youku1327",price=50.0) System.out.println(car); }
The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.