Java 8 method references
The method referenced by the method name to point to a method.
The method of reference configuration can be made more compact and concise language to reduce redundant code.
Method references a pair of colons (: :).
Below, we define four methods Car class as an example, the distinction between Java supported four different methods reference.
public static class Car { public static Car create( final Supplier< Car > supplier ) { return supplier.get(); } public static void collide( final Car car ) { System.out.println( "Collided " + car.toString() ); } public void follow( final Car another ) { System.out.println( "Following the " + another.toString() ); } public void repair() { System.out.println( "Repaired " + this.toString() ); } }
Static method references: The syntax is Class :: static_method, examples are as follows:
final Car car = Car.create( Car::new ); final List< Car > cars = Arrays.asList( car );
Any object method of a particular class Quote: It is Class :: method syntax examples are as follows:
cars.forEach( Car::collide );
Method references a specific object: it is instance :: method syntax examples are as follows:
cars.forEach( Car::repair );
Constructor Quote: The syntax is Class :: new, or more generally the Class <T> :: new examples are as follows:
final Car police = Car.create( Car::new ); cars.forEach( police::follow );
Method references instance of
In Java8Tester.java file enter the following code:
import java.util.List; import java.util.ArrayList; public class Java8Tester { public static void main(String args[]){ List names = new ArrayList(); names.add("Google"); names.add("w3big"); names.add("Taobao"); names.add("Baidu"); names.add("Sina"); names.forEach(System.out::println); } }
Example we will System.out :: println method as a static method to reference.
Implementation of the above script, output is:
$ javac Java8Tester.java $ java Java8Tester Google w3big Taobao Baidu Sina