Core Java

Java 8 Method Reference Example

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.

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 to File -> 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 a pom.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 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

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 the Method Reference and Lambda.

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));
	}
}

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

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 the Method Reference and Lambda.

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 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.

# Logs for 'MethodReferenceEx1' #
=================================
--------------------Using Lambda Expression----------------------
true

---------------------Using Method Reference---------------------
false

# Logs for 'MethodReferenceEx2' #
=================================
--------------------Using Lambda Expression----------------------
Addtion = 9
Subtraction = 53

---------------------Using Method Reference---------------------
Addtion = 9
Subtraction = 53

# Logs for 'MethodReferenceEx3' #
=================================
--------------------Using Lambda Expression----------------------
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY

---------------------Using Method Reference---------------------
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY

# 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 of Method References in Java8.

Download
You can download the full source code of this example here: Java8MethodReference

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).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Pawel
Pawel
4 years ago

Very pretty tutorial.

Back to top button