0% found this document useful (0 votes)
172 views12 pages

Java 8 Method Reference

This document provides an overview of method references in Java 8. It defines method references as a simplified shorthand for lambda expressions that refer to existing methods. There are three types of method references: references to static methods, instance methods of a particular object, and instance methods of an arbitrary object of a particular type. Examples are provided to illustrate each type, showing how method references make code more concise compared to equivalent lambda expressions. Constructor references are also introduced as a specialized type of method reference.

Uploaded by

asadfx
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
172 views12 pages

Java 8 Method Reference

This document provides an overview of method references in Java 8. It defines method references as a simplified shorthand for lambda expressions that refer to existing methods. There are three types of method references: references to static methods, instance methods of a particular object, and instance methods of an arbitrary object of a particular type. Examples are provided to illustrate each type, showing how method references make code more concise compared to equivalent lambda expressions. Constructor references are also introduced as a specialized type of method reference.

Uploaded by

asadfx
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 12

Java 8 Method References Tutorial with Examples

This tutorial explains the concept of Method References introduced in Java 8. It rst de nes method
references and explains its syntax. Next it looks at the 3 types of method references and explains each
of them with code examples.

De nition: A method reference is a simpli ed form (or short-hand) of a lambda expression. It speci es the
class name or the instance name followed by the method name. Instead of writing the lambda expression with
all the details such as parameter and return type, a method reference lets you create a lambda expression
from an existing method implementation.
Method Reference Syntax: <class or instance name>::<methodName>
Method Reference Example
Integer::parseInt is a method reference with the following charecteristics –
It is equivalent to the lambda –
(String str, Integer integer)->Integer.parseInt(str)
It can can be assigned to a functional interface Function<T ,R> like this –
Function<String,integer> intParser=Integer::parseInt
Above assignment is equivalent to the assignment of lambda expression of parseInt() –
Function<String,Integer> intParser =
(String str,Integer integer)->Integer.parseInt(str)

Thus, instead of the longer lambda expression, just its concise method reference can be assigned to a
functional interface instance.

Types of Method References


Type 1: Reference to a static method – If we intend to use a static method of a class then instead of writing
the lengthier lambda expresion we can just refer to the method via method references.
Lambda Syntax: (arguments) -> <ClassName>.<staticMethodName>(arguments);

Equivalent Method Reference: <ClassName> :: <staticMethodName>


Let us now see an example showing the usage of method reference for a static method –
Example 1: Reference to a static method
package com.javabrahman.java8;
import java.util.Arrays;
import java.util.List;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;

public class MethodReferenceExample {

public static void main(String args[]){


Function<String, Double> doubleConvertor=Double::parseDouble;
Function<String, Double> doubleConvertorLambda=(String s) -> Double.parseDouble(s);
System.out.println("double value using method reference-" +doubleConvertor.apply
("0.254");
System.out.println("double value using Lambda - "+ doubleConvertorLambda.apply
("0.254"));
}
}

 OUTPUT of the above code


double value using method reference –
0.254 double value using Lambda – 0.254
Explanation of the output
The lambda and method reference worked the same and printed the same double value for the same input
passed.

Type 2: Reference to an instance method of a particular object –


Lambda Syntax: (param, rest of params)-> (param).<instanceMethodName>(rest of
params)
Equivalent Method Reference: <ClassName> :: <staticMethodName>
Note: <ClassName> in method reference is the class of parameter named param.
Code Example:(Skeleton code being the same Type 1 – only giving the delta code below)

Example 2:Reference to an instance method of an object

Consumer<String> stringPrinter=System.out::println;
Consumer<String> stringPrinterLambda=(String s) -> System.out.println(s);
stringPrinter.accept("Print from method reference based instance");
stringPrinterLambda.accept("Print from instance created from Lambda");

 OUTPUT of the above code


Print from method reference based instance
Print from instance created from Lambda
Explanation of the output
The lambda and method reference worked the same and printed the string value passed to them.

Type 3: Reference to an instance method of an arbitrary object of a particular type– Here the method
reference used is of an instance method of an existing object.
Lambda Syntax: (arguments) -> <expression>.<instanceMethodName>(arguments)
Equivalent Method Reference: <expression> :: <instanceMethodName>
Code Example(Skeleton code being the same Type 1 – only giving the delta code below)

Example 3:Reference to an instance method of an arbitrary object of a


particular type

List<Integer> intList=Arrays.asList(1,2,3,4);
BiPredicate<List>Integer>,Integer> isPartOf=List::contains;
BiPredicate<List<Integer>,Integer> isPartOfLambda=(List<Integer> listInt,
Integer value) -> listInt.contains(value);
System.out.println("Is 1 a part of the intList - "+ isPartOf.test(intList,1));
System.out.println("Is 1 a part of the intList - "+ isPartOfLambda.test(intList, 1));

 OUTPUT of the above code


Is 1 a part of the intList – true
Is 1 a part of the intList – true
Explanation of the output
The lambda and method reference worked the same and printed the same boolean value ‘true’ for the same
input passed.

Note – There is a 4th type of specialized method reference called Constructor Reference. I have written a
separate article explaining Constructor References.

Summary
The above tutorial explained java 8 method references including their de nition, syntax and the 3 types of
method references with detailed code examples.
Constructor References Java 8 Simplified Tutorial with
examples
This tutorial explains the new Java 8 feature known as constructor reference. It starts off with
explaining what is a constructor reference by showing its structure and an example. Next, the tutorial
shows an example scenario where constructor references can be applied for instantiating objects from
an object factory.
(Note – If you are new to the concept of method references then I would recommend that rst refer the
method references tutorial.)

What are Constructor References: Constructor Introduced in Java 8, constructor references are
specialized form of method references which refer to the constructors of a class. Constructor References can
be created using the Class Name and the keyword new with the following syntax –
Syntax of Constructor References: <ClassName>::new

Constructor Reference Example: If you want reference to the constructor of wrapper class Integer, then
you can write something like this –
Supplier<Integer> integerSupplier = Integer::new

Example usage of Constructor References in code


STEP 1 – Let us de ne an Employee class with a constructor having 2 parameters as shown below –

Employee.java

public class Employee{


String name;
Integer age;
//Contructor of employee
public Employee(String name, Integer age){

this.name=name;
this.age=age;
}
}

STEP 2 – Now lets create a factory interface for employees called EmployeeFactory. getEmployee()
method of EmployeeFactory will return an employee instance as per the normal design of factory pattern.
Interface EmployeeFactory.java

public Interface EmployeeFactory{


public abstract Employee getEmployee(String name, Integer age);
}

Note – Since EmployeeFactory interface has a single abstract method hence it is a Functional Interface.

STEP 3 – The client side code to invoke EmployeeFactory to create Employee instances would be as
follows –

Client-side code for invoking Factory interface

EmployeeFactory empFactory=Employee::new;
Employee emp= empFactory.getEmployee("John Hammond", 25);

Explanation of the code


The Constructor Reference of Employee is assigned to an instance of EmployeeFactory called
empFactory. This is possible because the function descriptor of Employee constructor is same as that
of the abstract method of the Functional Interface EmployeeFactory i.e.
(String, Integer) ->Employee.

Then the getEmployee method of empFactory is called with John’s name and age which internally
calls the constructor of Employee and a new Employee instance emp is created.

Summary: In the above tutorial we understood constructor references by rst understanding their
de nition/structure. Next we saw examples for de ning a constructor reference for actual usage and then saw
an example practical scenario where constructor references can be used.
Java 8 Method Reference Example
Posted by: Yatin in Core Java January 22nd, 2018 0 904 Views

Hello readers, Java provides a new feature called method reference in Java8. This
tutorial explains the method reference concept in detail.

1. Introduction
Lambda Expression allows developers to reduce the code compared to the anonymous
class in order to pass behaviors to the methods, Method Reference goes one step
further. It reduces the code written in a lambda expression to make it even more
readable and concise. Developers use the lambda expressions to create the anonymous
methods.
Sometimes, however, a lambda expression does nothing but call an existing method. In
those cases, it’s often clearer to refer to the existing method by name. Method
References enable the developers to achieve this and thus they
are compact and easy-to-read lambda expressions for methods that already have a
name.

1.1 What is Method Reference?


It is a feature which is related to the Lambda Expression. It allows us to reference the
constructors or methods without executing them. Method references and Lambda are
similar in that they both require a target type that consists of a compatible functional
interface. Sometimes, a lambda expression does nothing but call an existing method as
follows.
Predicate predicate1 = (n) -> EvenOddCheck.isEven(n);
Using method references, developers can write the above lambda expression as follows.
Predicate predicate2 = EvenOddCheck::isEven;
It is clear from the above statement that method references enable developers to
write a lambda expression in more compact and readable form. Double-colon operator
i.e. ( :: ) is used for method references.

Note: The ‘target type‘ for a method reference and lambda expression must be
a Functional Interface (i.e. an abstract single method interface).

1.1.1 When to use Method Reference?


When a Lambda expression is invoking an already defined method, developers can
replace it with a reference to that method.
1.1.2 When you cannot use Method Reference?
Developers cannot pass arguments to the method reference. For e.g., they cannot use
the method reference for the following lambda expression.
IsReferable demo = () -> ReferenceDemo.commonMethod("Argument in method.");
Because Java does not support currying without the wrapper methods or lambda.

1.1.3 Types of Method Reference


There are four types of method reference and the table below summarizes this.
Type Example Syntax

Reference to a Static ContainingClass::staticMethodName Class::staticMethodName


Method

Reference to a ClassName::new ClassName::new


Constructor

Reference to an Instance ContainingType::methodName Class::instanceMethodName


Method of an Arbitrary
Object of a Particular
Type

Reference to an Instance containingObject::instanceMethodName object::instanceMethodName


Method of a Particular
Object

Now, open up the Eclipse Ide and I will explain further about the four types of method
referenced in the table.

3. Java8 Method Reference Example


3.1 Java Class Implementation
Here are the complete examples of how to use the Method References in Java
programming.

3.1.1 Reference to a Static Method


In the following example, we have defined a functional interface and referring a static
method to its functional method say isEven() . Let’s see the simple code snippet that
follows this implementation and list the difference between the Method
Reference and Lambda.

MethodReferenceEx1.java
01 package com.jcg.java;
02
/**** Functional Interface ****/
03 interface Predicate {
04 boolean test(int n);
05 }
06
07 class EvenOddCheck {
public static boolean isEven(int n) {
08 return n % 2 == 0;
09 }
10 }
11
12 /***** Reference To A Static Method *****/
public class MethodReferenceEx1 {
13
14 public static void main(String[] args) {
15
16 /**** Using Lambda Expression ****/
17 System.out.println("--------------------Using Lambda Expression---“);
18 Predicate predicate1 = (n) -> EvenOddCheck.isEven(n);
19 System.out.println(predicate1.test(20));
20
/**** Using Method Reference ****/
21 System.out.println("\n---------------------Using Method Reference---");
22 Predicate predicate2 = EvenOddCheck::isEven;
23 System.out.println(predicate2.test(25));
24 }
}
25
26
27
28
29
As developers can see in this code, we made reference to a static method in this class
i.e.
• ContainingClass : EvenOddCheck
• staticMethodName : isEven

3.1.2 Reference to an Instance Method of a Particular Object


Here is an example of using method reference to an instance method of a particular
object. Let’s see the simple code snippet that follows this implementation and list the
difference between the Method Reference and Lambda.
MethodReferenceEx2.java
01 package com.jcg.java;
02
03 import java.util.function.BiFunction;
04
class MathOperation {
05
06 /**** Addition ****/
07 public int add(int a, int b) {
08 return a + b;
09 }
10
11 /**** Subtraction ****/
12 public int sub(int a, int b) {
return a - b;
13 }
14 }
15
16 /***** Reference To An Instance Method Of A Particular Object *****/
17 public class MethodReferenceEx2 {
18
public static void main(String[] args) {
19
20 MathOperation op = new MathOperation();
21
22 /**** Using Lambda Expression ****/
23 System.out.println("--------------------Using Lambda Expression------");
24 BiFunction<Integer, Integer, Integer> add1 = (a, b) -> op.add(a, b);
25 System.out.println("Addtion = " + add1.apply(4, 5));
26
BiFunction<Integer, Integer, Integer> sub1 = (a, b) -> op.sub(a, b);
27 System.out.println("Subtraction = " + sub1.apply(58, 5));
28
29 /**** Using Method Reference ****/
30 System.out.println("\n---------------------Using Method Reference-----");
31 BiFunction<Integer, Integer, Integer> add2 = op::add;
System.out.println("Addtion = " + add2.apply(4, 5));
32
33 BiFunction<Integer, Integer, Integer> sub2 = op::sub;
34 System.out.println("Subtraction = " + sub2.apply(58, 5));
35 }
36 }
37
38
39
40
41
Since System.out is an instance of type PrintStream , we then call the println method of
the instance.
• ContainingObject : System.out
• instanceMethodName : println

3.1.3 Reference to an Instance Method of an Arbitrary Object of a


Particular Type
Here is an example of using method reference to an instance method of an arbitrary
object of a particular type. Let’s see the simple code snippet that follows this
implementation and list the difference between the Method Reference and Lambda.
MethodReferenceEx3.java
01
02
03 package com.jcg.java;
04
import java.util.ArrayList;
05
import java.util.List;
06
07 /***** Reference To An Instance Method Of An Arbitrary Object Of A Particular Type **
08 public class MethodReferenceEx3 {
09
10 public static void main(String[] args) {
11
12 List<String> weeks = new ArrayList<String>();
weeks.add("Monday");
13 weeks.add("Tuesday");
14 weeks.add("Wednesday");
15 weeks.add("Thursday");
16 weeks.add("Friday");
17 weeks.add("Saturday");
weeks.add("Sunday");
18
19 /**** Using Lambda Expression ****/
20 System.out.println("--------------------Using Lambda Expression----------");
21 weeks.stream().map((s)-> s.toUpperCase()).forEach((s)->System.out.println(s));
22
23 /**** Using Method Reference ****/
System.out.println("\n---------------------Using Method Reference--------");
24 weeks.stream().map(String::toUpperCase).forEach(System.out::println);
25 }
26 }
27
28

3.1.4 Reference to a Constructor


Here is an example of using method reference to a constructor. Let’s see the simple
code snippet that follows this implementation and list the difference between
the Method Reference and Lambda.
MethodReferenceEx4.java
package com.jcg.java;
01
02 import java.util.function.BiConsumer;
03
04 class MathOperations {
05
06 public MathOperations(int a, int b) {
07 System.out.println("Sum of " + a + " and " + b + " is " + (a + b));
08 }
}
09
10 /***** Reference To A Constructor *****/
11 public class MethodReferenceEx4 {
12
13 public static void main(String[] args) {
14
/**** Using Lambda Expression ****/
15 System.out.println("--------------------Using Lambda Expression--------");
16 BiConsumer<Integer, Integer> addtion1 = (a, b) -> new MathOperations(a, b);
17 addtion1.accept(10, 20);
18
19 /**** Using Method Reference ****/
System.out.println("\n---------------------Using Method Reference-------");
20 BiConsumer<Integer, Integer> addtion2 = MathOperations::new;
21 addtion2.accept(50, 20);
22 }
23 }
24
25
26
27
This approach is very similar to a static method. The difference between the two is that
the constructor reference method name is new i.e.
• ClassName: Integer
• new : new

4. Run the Application


To run the application, developers need to right-click on the classes i.e. Run As -> Java
Application . Developers can debug the example and see what happens after every
step!

5. Project Demo
The application shows the following logs as output.
01 # Logs for 'MethodReferenceEx1' #
02 =================================
--------------------Using Lambda Expression----------------------
03 true
04
05 ---------------------Using Method Reference---------------------
06 false
07
08 # Logs for 'MethodReferenceEx2' #
09 =================================
--------------------Using Lambda Expression----------------------
10 Addtion = 9
11 Subtraction = 53
12
13 ---------------------Using Method Reference---------------------
14 Addtion = 9
15 Subtraction = 53
16
# Logs for 'MethodReferenceEx3' #
17 =================================
18 --------------------Using Lambda Expression----------------------
19 MONDAY
20 TUESDAY
WEDNESDAY
21 THURSDAY
22 FRIDAY
23 SATURDAY
24 SUNDAY
25
26 ---------------------Using Method Reference---------------------
MONDAY
27 TUESDAY
28 WEDNESDAY
29 THURSDAY
30 FRIDAY
SATURDAY
31 SUNDAY
32
33 # Logs for 'MethodReferenceEx4' #
34 =================================
35 --------------------Using Lambda Expression----------------------
36 Sum of 10 and 20 is 30
37
---------------------Using Method Reference---------------------
38 Sum of 50 and 20 is 70
39
40
41
42
43
44
45
That’s all for this post. Happy Learning!

6. Conclusion
In this tutorial:
• Developers can replace the Lambda Expressions with Method References where
Lambda is invoking already defined methods
• Developers can’t pass arguments to Method References
• To use Lambda and Method Reference, make sure you have Java8 (i.e. ‘JDK 1.8’)
installed. They do not work on Java7 and earlier versions
I hope this article served developers whatever they were looking for.

You might also like