Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java 8 Method References

Java 8 Method References

Java 8 New Features Java 8 New Features


A method reference points to a method by its name.

Method references make language constructs more compact and concise, reducing redundant code.

Method references use a pair of colons :: .

Below, we define 4 methods in the Car class as examples to distinguish the 4 different kinds of method references in Java.

package

com

.

runoob

.

main

; @

FunctionalInterface

public

interface

Supplier

<
T
{
T
get
(
)

;

}

class

Car

{

//

Supplier is a jdk1.8 interface, used here together with lambda

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

(

)

)

;

}

}

final Car car = Car.create( Car::new ); final List< Car > cars = Arrays.asList( car );
-

Static method reference:Its syntax is Class::static_method, as in the following example:

cars.forEach( Car::collide );
-

Method reference to any object of a particular class:Its syntax is Class::method, as in the following example:

cars.forEach( Car::repair );
-

Method reference to a particular object:Its syntax is instance::method, as in the following example:

final Car police = Car.create( Car::new ); cars.forEach( police::follow );

Method Reference Example

Enter the following code in the Java8Tester.java file:

Java8Tester.java file

import

java

.

util

.

List

;

import

java

.

util

.

ArrayList

;

public

class

Java8Tester

{

public

static

void

main

(

String

args

[

]

)

{

List

<
String
names
=
new
ArrayList
(
)

;

names

.

add

(

"

Google

"

)

;

names

.

add

(

"

Runoob

"

)

;

names

.

add

(

"

Taobao

"

)

;

names

.

add

(

"

Baidu

"

)

;

names

.

add

(

"

Sina

"

)

;

names

.

forEach

(

System

.

out

::

println

)

;

}

}

In the example we reference the System.out::println method as a static method.

Executing the above script produces the following output:


$ javac Java8Tester.java 
$ java Java8Tester
Google
Runoob
Taobao
Baidu
Sina

Java 8 New Features Java 8 New Features