Core Java

Java 8 Method Reference Example

Photo of YatinYatinJanuary 22nd, 2018Last Updated: February 25th, 2019
1 398 6 minutes read

Hello readers, Java provides a new feature calledmethod 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 arecompact andeasy-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 thatmethod referencesenable 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 amethod reference andlambda expression must be aFunctional 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 supportcurrying 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.

TypeExampleSyntax
Reference to a Static MethodContainingClass::staticMethodNameClass::staticMethodName
Reference to a ConstructorClassName::newClassName::new
Reference to an Instance Method of an Arbitrary Object of a Particular TypeContainingType::methodNameClass::instanceMethodName
Reference to an Instance Method of a Particular ObjectcontainingObject::instanceMethodNameobject::instanceMethodName

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

2. Java8 Method Reference Example

2.1 Tools Used

We are using Eclipse Oxygen, JDK 1.8 and Maven.

2.2 Project Structure

Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Fig. 1: Application Project Structure
Fig. 1: Application Project Structure

2.3 Project Creation

This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go toFile -> New -> Maven Project.

Fig. 2: Create Maven Project
Fig. 2: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ checkbox and just click on next button to proceed.

Fig. 3: Project Details
Fig. 3: Project Details

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default:0.0.1-SNAPSHOT.

Fig. 4: Archetype Parameters
Fig. 4: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and apom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>Java8MethodReference</groupId><artifactId>Java8MethodReference</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging></project>

Developers can start adding the dependencies that they want. Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Java Class Implementation

Here are the complete examples of how to use theMethod 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 sayisEven(). Let’s see the simple code snippet that follows this implementation and list the difference between theMethod Reference andLambda.

MethodReferenceEx1.java

package com.jcg.java;/**** Functional Interface ****/interface Predicate {boolean test(int n);}class EvenOddCheck {public static boolean isEven(int n) {return n % 2 == 0;}}/***** Reference To A Static Method *****/public class MethodReferenceEx1 {public static void main(String[] args) {/**** Using Lambda Expression ****/System.out.println("--------------------Using Lambda Expression----------------------");Predicate predicate1 = (n) -> EvenOddCheck.isEven(n);System.out.println(predicate1.test(20));/**** Using Method Reference ****/System.out.println("\n---------------------Using Method Reference---------------------");Predicate predicate2 = EvenOddCheck::isEven;System.out.println(predicate2.test(25));}}

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 theMethod Reference andLambda.

MethodReferenceEx2.java

package com.jcg.java;import java.util.function.BiFunction;class MathOperation {/**** Addition ****/public int add(int a, int b) {return a + b;}/**** Subtraction ****/public int sub(int a, int b) {return a - b;}}/***** Reference To An Instance Method Of A Particular Object *****/public class MethodReferenceEx2 {public static void main(String[] args) {MathOperation op = new MathOperation();/**** Using Lambda Expression ****/System.out.println("--------------------Using Lambda Expression----------------------");BiFunction<Integer, Integer, Integer> add1 = (a, b) -> op.add(a, b);System.out.println("Addtion = " + add1.apply(4, 5));BiFunction<Integer, Integer, Integer> sub1 = (a, b) -> op.sub(a, b);System.out.println("Subtraction = " + sub1.apply(58, 5));/**** Using Method Reference ****/System.out.println("\n---------------------Using Method Reference---------------------");BiFunction<Integer, Integer, Integer> add2 = op::add;System.out.println("Addtion = " + add2.apply(4, 5));BiFunction<Integer, Integer, Integer> sub2 = op::sub;System.out.println("Subtraction = " + sub2.apply(58, 5));}}

SinceSystem.out is an instance of typePrintStream, we then call theprintln method of the instance.

Want to be a Java 8 Ninja ?
Subscribe to our newsletter and download the Java 8 FeaturesUltimateGuideright now!
In order to get you up to speed with the major Java 8 release, we have compiled a kick-ass guide with all the new features and goodies! Besides studying them online you may download the eBook in PDF format!

Thank you!

We will contact you soon.

  • 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 theMethod Reference andLambda.

MethodReferenceEx3.java

package com.jcg.java;import java.util.ArrayList;import java.util.List;/***** Reference To An Instance Method Of An Arbitrary Object Of A Particular Type *****/public class MethodReferenceEx3 {public static void main(String[] args) {List<String> weeks = new ArrayList<String>();weeks.add("Monday");weeks.add("Tuesday");weeks.add("Wednesday");weeks.add("Thursday");weeks.add("Friday");weeks.add("Saturday");weeks.add("Sunday");/**** Using Lambda Expression ****/System.out.println("--------------------Using Lambda Expression----------------------");weeks.stream().map((s)-> s.toUpperCase()).forEach((s)->System.out.println(s));/**** Using Method Reference ****/System.out.println("\n---------------------Using Method Reference---------------------");weeks.stream().map(String::toUpperCase).forEach(System.out::println);}}

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 theMethod Reference andLambda.

MethodReferenceEx4.java

package com.jcg.java;import java.util.function.BiConsumer;class MathOperations {public MathOperations(int a, int b) {System.out.println("Sum of " + a + " and " + b + " is " + (a + b));}}/***** Reference To A Constructor *****/public class MethodReferenceEx4 {public static void main(String[] args) {/**** Using Lambda Expression ****/System.out.println("--------------------Using Lambda Expression----------------------");BiConsumer<Integer, Integer> addtion1 = (a, b) -> new MathOperations(a, b);addtion1.accept(10, 20);/**** Using Method Reference ****/System.out.println("\n---------------------Using Method Reference---------------------");BiConsumer<Integer, Integer> addtion2 = MathOperations::new;addtion2.accept(50, 20);}}

This approach is very similar to a static method. The difference between the two is that the constructor reference method name isnew 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.

# Logs for 'MethodReferenceEx1' #=================================--------------------Using Lambda Expression----------------------true---------------------Using Method Reference---------------------false# Logs for 'MethodReferenceEx2' #=================================--------------------Using Lambda Expression----------------------Addtion = 9Subtraction = 53---------------------Using Method Reference---------------------Addtion = 9Subtraction = 53# Logs for 'MethodReferenceEx3' #=================================--------------------Using Lambda Expression----------------------MONDAYTUESDAYWEDNESDAYTHURSDAYFRIDAYSATURDAYSUNDAY---------------------Using Method Reference---------------------MONDAYTUESDAYWEDNESDAYTHURSDAYFRIDAYSATURDAYSUNDAY# Logs for 'MethodReferenceEx4' #=================================--------------------Using Lambda Expression----------------------Sum of 10 and 20 is 30---------------------Using Method Reference---------------------Sum of 50 and 20 is 70

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.

7. Download the Eclipse Project

This was an example ofMethod References in Java8.

Download
You can download the full source code of this example here:Java8MethodReference
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of YatinYatinJanuary 22nd, 2018Last Updated: February 25th, 2019
1 398 6 minutes read
Photo of Yatin

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).

Related Articles

Bipartite Graph

Java not equal Example

January 17th, 2020
Bipartite Graph

Java API Tutorial

October 26th, 2020
Bipartite Graph

Java Struct Example

January 8th, 2020
Bipartite Graph

Java Node Example

November 20th, 2019
Bipartite Graph

Java Swing MVC Example

January 26th, 2016
Bipartite Graph

How to call a method in Java

December 26th, 2019
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.