Java 8 Method Reference
Java 8 Method Reference
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.
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");
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)
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));
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
Employee.java
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
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 –
EmployeeFactory empFactory=Employee::new;
Employee emp= empFactory.getEmployee("John Hammond", 25);
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.
Note: The ‘target type‘ for a method reference and lambda expression must be
a Functional Interface (i.e. an abstract single method interface).
Now, open up the Eclipse Ide and I will explain further about the four types of method
referenced in the table.
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
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.